1
Vote

EF CodeFirst - Models for standard tables

description

Hi,
 
I just set this up with a new MVC3 database using EF 4.1 code-first.
 
Setting up the tables wasn't hard but took a few mins so it might be nice to either include a sample DbContext or include the models in the wiki so people can cut and paste.
 
I've included my models below, which I've just finished so haven't had much testing but look on in Sql Server.
 
Thanks for the excellent package,
 
Paul
 
 
public class DataContext : DbContext
{
 
    public IDbSet<User> Users { get; set; }
    public IDbSet<Role> Roles { get; set; }
    public IDbSet<RoleMembership> RoleMemberships { get; set; }
 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<RoleMembership>().HasRequired(rm => rm.Role).WithOptional().Map(a => a.MapKey("RoleName"));
        base.OnModelCreating(modelBuilder);
    }
}
 
public class User
{
    [Key]
    [StringLength(100)]
    public string UserName { get; set; }
    [Required]
    [MaxLength(64)]
    [Column(TypeName="binary")]
    public byte[] PasswordHash { get; set; }
    [Required]
    [MaxLength(128)]
    [Column(TypeName = "binary")]
    public byte[] PasswordSalt { get; set; }
    [Required]
    public string Email { get; set; }
    public string Comment { get; set; }
    public bool IsApproved { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime? DateLastLogin { get; set; }
    public DateTime? DateLastActivity { get; set; }
    [Required]
    public DateTime DateLastPasswordChange { get; set; }
}
 
public class Role
{
    [StringLength(100)]
    [Required]
    [Key]
    public string RoleName { get; set; }
}
 
public class RoleMembership
{
    [StringLength(100)]
    [Required]
    [Key]
    public string UserName { get; set; }
    [Required]
    [Key]
    public Role Role { get; set; }
}

comments