实体关系 | Has | With | ForeignKey |
一对一 | .HasRequired | .WithMany | .HasForeignKey |
一对多 | .HasMany | .WithRequired | |
多对多 | .HasMany | .WithMany | MapLeftKey,MapRightKey,ToTable |
在继承DbContext类中,重写下面的方法,对两个POCO之间关系描述。
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<User>().HasMany(u => u.Roles) .WithMany(r => r.Users) .Map( m => { m.MapLeftKey("UserId"); m.MapRightKey("RoleId"); m.ToTable("UserRoles"); }); modelBuilder.Entity<Role>().HasMany(r => r.ControllerActions) .WithMany(c => c.Roles) .Map( m => { m.MapLeftKey("RoleId"); m.MapRightKey("ControllerActionId"); m.ToTable("RoleControllerAction"); });
联合主键:
1.modelBuilder.Entity<BlogPost_Category>() 2. .HasKey(it => it.BlogPostId) 3. .HasKey(it => it.CategoryId);