Asp.net 实体框架中的多对多关系
我与多对多关系有问题 我有3个模型课:Asp.net 实体框架中的多对多关系,asp.net,asp.net-mvc,entity-framework,many-to-many,Asp.net,Asp.net Mvc,Entity Framework,Many To Many,我与多对多关系有问题 我有3个模型课: 文章->>>项目 关键字->>>关键字 TableForArticles与关键字之间的关系->>>ItemKeywords 使用Entity Framework Core,我编写了这3个类,它们工作得很好 public class Item { public int Id { get; set; } public string Content { get; set; } public virtual ICollecti
public class Item
{
public int Id { get; set; }
public string Content { get; set; }
public virtual ICollection<ItemKeyWords> ItemKeyWords { get; set; }
}
public class KeyWord
{
public int Id { get; set }
public string Text { get; set; }
public virtual ICollection<ItemKeyWords> ItemKeyWords { get; set; }
}
public class ItemKeyWords
{
public int Id { get; set; }
public int ItemId { get; set; }
public virtual Item Item { get; set; }
public int KeyWordId { get; set; }
public virtual KeyWord KeyWord { get; set; }
}
公共类项目
{
公共int Id{get;set;}
公共字符串内容{get;set;}
公共虚拟ICollection项关键字{get;set;}
}
公共类关键字
{
公共int Id{get;set}
公共字符串文本{get;set;}
公共虚拟ICollection项关键字{get;set;}
}
公共类项目关键字
{
公共int Id{get;set;}
公共int ItemId{get;set;}
公共虚拟项项{get;set;}
public int关键字id{get;set;}
公共虚拟关键字{get;set;}
}
问题是:我如何判断实体框架是否存在关键字
,不要将其放在关键字表中,而只是创建一个与ItemKeywords表中的关键字的关系
在将
关键字添加到项目之前。ItemKeyWords
您必须尝试从上下文.Set()加载它
如果加载结果为null,则按实际操作
如果加载失败!=空,然后添加加载的值。我这样做了,并为我工作。thx,还有更好的方法吗?如果您知道关键字的id,您可以使用它来构造关键字实体并将其附加到上下文中。然后使用附加的实体将关键字添加到项目中。这样做可以避免对数据库造成影响。