Nov 25, 2014
1 min read
兩個類別之間,各自包含對應的集合導覽屬性,就會被當成多對多關系 在資料庫中的多對多關系,需要用三張表來表示,分別是一對多再多對一
一個使用者可以有多個群組
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"); }); } }
}
Sharing is caring!