Entity Framework Many to Many Relation Mapping(Entity Framework多對多關係映射)

來源:互聯網
上載者:User

標籤:資料   builder   asm   first   mode   datetime   byte   base   重載方法   

    通常我們在做資料庫設計時都會有兩張表是多對多關係的時候,在資料庫做多對多關係時候我們通常通過中間關聯表來處理,那我們現在在EF中是如何處理的呢?

    假設我們有如下關係,使用者(User)包含多個角色(Role),角色包含多個使用者的情況下,我們如何用EF來處理這樣的資料庫設計呢?

接下來看如下代碼清單:

首先看我們的UserRole實體

 1 public class User 2  3 { 4  5     public User() {} 6  7   8  9     public int UserId { get; set; }10 11     public string Name { get; set; }12 13     public string Password { get; set; }14 15     public string PasswordSalt { get; set; }16 17     public Byte Status { get; set; }18 19     public DateTime CreatedDate { get; set; }20 21     public DateTime ModifiedDate { get; set; }22 23 }24 25 public class Role26 27 {28 29      public Role() {}30 31      public int RoleId { get; set; }32 33      public string RoleName { get; set; }34 35 }

接下來,我們知道使用者包含多個角色,那麼在User實體中添加這樣的代碼

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

 

User的建構函式中添加這樣代碼

this.Roles = new HashSet<Role>();

 

同樣的,角色也包含多個使用者,那麼在Role實體中添加這樣代碼

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

 

Role建構函式中添加這樣代碼

this.Users = new HashSet<User>();

 

接下來,構造我們繼承自DbContext類的DataContext

public class DataContext : DbContext{    public DataContext()        : base("DataContext")    {    }    public DbSet<User> Users { get; set; }    public DbSet<Role> Roles { get; set; }    protected override void OnModelCreating(DbModelBuilder modelBuilder)    {            }}

 

接著,我們產生我們項目,就可以看到我們產生的資料庫關係了

可以看到我們中間的連結資料表產生的是User_UserIdRole_RoleId,但實際工作中我們可能不會這樣定義或者希望可以更多定製化,接下來我們通過Fluent API(註:我這裡直譯為流暢的API聲明,大家可以看字面意思理解,我不一定對)方式來進行資料聲明,我們這裡關係是一個使用者可以包含多個角色,一個角色也可以包含多個使用者,那我們在DataContextOnModelCreating重載方法裡這樣寫:

modelBuilder.Entity<User>()    .HasMany(r => r.Roles).WithMany(u => u.Users);

 

進一步我們指定中間連結資料表

 modelBuilder.Entity<User>()     .HasMany(r => r.Roles)     .WithMany(u => u.Users)     .Map(ur =>     {         ur.MapLeftKey("UserId");         ur.MapRightKey("RoleId");         ur.ToTable("UserRoles");     });

 

參考資料:

http://www.cnblogs.com/panchunting/p/entity-framework-code-first-fluent-api-configuring-relationships.html

Entity Framework Many to Many Relation Mapping(Entity Framework多對多關係映射)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.