Entity Framework Code First 多對多關聯設定

兩個類別之間,各自包含對應的集合導覽屬性,就會被當成多對多關系
在資料庫中的多對多關系,需要用三張表來表示,分別是一對多再多對一

一個使用者可以有多個群組

namespace ConsoleApplication1.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

[Table(“User”)]
public class User
{
public int UserId { get; set; }

public string UserName { get; set; }

public virtual ICollection<Group> Group { get; set; }
}
}

一個群組可以有多個使用者
namespace ConsoleApplication1.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

[Table(“Group”)]
public class Group
{
public int GroupId { get; set; }

public string GroupName { get; set; }

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

預設會自動生成第三張表

透過FluentAPI設定第三張表的名稱,和欄位名稱

namespace ConsoleApplication1.Models
{
using System.Data.Entity;

public class DemoContext : DbContext
{
public DbSet<User> User { get; set; }

public DbSet<Group> Group { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(x => x.Group)
.WithMany(x => x.User)
.Map(x =>{
x.ToTable(“MyUserGroup”);
x.MapLeftKey(“UserID”);
x.MapRightKey(“GroupID”);
});
}
}
}

資料表建立的樣子

關聯圖