2013-05-03 26 views
3

我使用實體代碼優先創建數據庫和表來存儲用戶,角色和UserRoles。實體代碼第一個用戶,角色,UserRole表

我的類如下 -

public class User 
    { 
     public int UserId { get; set; } 
     public string Username { get; set; } 
     public string Password { get; set; } 
    } 


public class Role 
{ 
     public int RoleId { get; set; } 
     public string Rolename { get; set; } 
} 


public class UserRole 
{ 
    public int UserRoleId { get; set; } 
    public int UserId { get; set; } 
    public int RoleId { get; set; } 

    public virtual User User { get; set; } 
    public virtual Role Role { get; set; } 
} 

class ConfigurationContext : DbContext 
{ 
    public ConfigurationContext() 
    { 
     Database.SetInitializer<ConfigurationContext>(new DropCreateDatabaseIfModelChanges<ConfigurationContext>()); 
    } 

    public DbSet<Role> Roles { get; set; } 
    public DbSet<User> Users { get; set; } 
    public DbSet<UserRole> UserRoles { get; set; } 
} 

我的目的是通過表格的UserRole將用戶連接到角色。

我可以通過創建表格並使用CF Reverse Engineer Tool來完成此操作,但這會產生大量多餘代碼,並想知道如何幹淨地完成此操作。

回答

7

您不需要UserRole實體。 EF可以通過在沒有該實體的情況下在數據庫中創建適當的鏈接表來自動管理多對多關係。

最簡單的解決方案就是將兩個集合添加到UserRole實體中。 EF會檢測按約定一個多一對多的關係沒有進一步明確的配置:

public class User 
{ 
    public int UserId { get; set; } 
    public string Username { get; set; } 
    public string Password { get; set; } 

    public virtual ICollection<Role> Roles { get; set; } 
} 

public class Role 
{ 
    public int RoleId { get; set; } 
    public string Rolename { get; set; } 

    public virtual ICollection<User> Users { get; set; } 
} 

class ConfigurationContext : DbContext 
{ 
    public ConfigurationContext() 
    { 
     Database.SetInitializer<ConfigurationContext>(
      new DropCreateDatabaseIfModelChanges<ConfigurationContext>()); 
    } 

    public DbSet<Role> Roles { get; set; } 
    public DbSet<User> Users { get; set; } 
} 

如果你不需要或不想要的收藏品之一,說你不想Role.Users,那麼你仍然可以創建只有一個集合許多一對多的關係,用流利的API定義它:

public class User 
{ 
    public int UserId { get; set; } 
    public string Username { get; set; } 
    public string Password { get; set; } 

    public virtual ICollection<Role> Roles { get; set; } 
} 

public class Role 
{ 
    public int RoleId { get; set; } 
    public string Rolename { get; set; } 
} 

class ConfigurationContext : DbContext 
{ 
    public ConfigurationContext() 
    { 
     Database.SetInitializer<ConfigurationContext>(
      new DropCreateDatabaseIfModelChanges<ConfigurationContext>()); 
    } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<User>() 
      .HasMany(u => u.Roles) 
      .WithMany() 
      .Map(m => { 
       m.ToTable("UserRoles"); 
       m.MapLeftKey("UserId"); 
       m.MapRightKey("RoleId"); 
      }); 
    } 

    public DbSet<Role> Roles { get; set; } 
    public DbSet<User> Users { get; set; } 
} 
0

CF逆向工程工具,但產生大量的多餘代碼和 想知道如何幹淨地做到這一點。

絕對同意。我的方法是使用Entity Framework Power Tools,但仍然有時需要手動選擇乾淨的代碼。 如何創建角色和用戶之間的多對多關係我已經回答了here。而且你不需要UserRole實體。

相關問題