栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

多对多映射表

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

多对多映射表

在您的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));


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/576053.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号