在您的DbContext OnModelCreating上执行此 *** 作:
protected override void onModelCreating(DbModelBuilder modelBuilder){ modelBuilder.Entity<Recipe>() .HasMany(x => x.Members) .WithMany(x => x.Recipes) .Map(x => { x.ToTable("Cookbooks"); // third table is named Cookbooks x.MapLeftKey("RecipeId"); x.MapRightKey("MemberId"); });}
您也可以用另一种方法来做,就是一样,只是同一枚硬币的另一面:
modelBuilder.Entity<Member>() .HasMany(x => x.Recipes) .WithMany(x => x.Members).Map(x =>{ x.ToTable("Cookbooks"); // third table is named Cookbooks x.MapLeftKey("MemberId"); x.MapRightKey("RecipeId");});
进一步的例子:
http://www.ienablemuch.com/2011/07/using-checkbox-list-on-aspnet-mvc-
with_16.html
http://www.ienablemuch.com/2011/07/nhibernate-equivalent-of-
entity.html
更新
为了防止对Author属性进行周期性引用,除了上面的内容外,您还需要添加以下内容:
modelBuilder.Entity<Recipe>() .HasRequired(x => x.Author) .WithMany() .WillCascadeonDelete(false);
想法来源:EF代码优先,具有多对多自引用关系
核心是,您需要通知EF
Author属性(这是一个Member实例)没有Recipe集合(用表示
WithMany());这样,可以在Author属性上停止循环引用。
这些是从上面的“代码优先”映射创建的表:
CREATE TABLE Members( Id int IDENTITY(1,1) NOT NULL primary key, Name nvarchar(128) NOT NULL);CREATE TABLE Recipes( Id int IDENTITY(1,1) NOT NULL primary key, Name nvarchar(128) NOT NULL, AuthorId int NOT NULL references Members(Id));CREATE TABLE Cookbooks( RecipeId int NOT NULL, MemberId int NOT NULL, constraint pk_Cookbooks primary key(RecipeId,MemberId));
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)