我有两个实体框架代码第一个POCO。我可以轻松地将新的站点和技术项目插入到数据库中,但我似乎无法将站点与技术相关联。当我这样做......
if(!site.Technologies.Any( o => (o.Name == technology.Name && technology.Source == source)))
{
site.Technologies.Add(technology);
technology.Sites.Add(site);
}
我收到重复的密钥错误。如果我从条件中删除第二行,则连接表TechnologiesSites不会获得任何记录!如何在EF Code First中插入?
public class Site
{
public Site()
{
Technologies = new HashSet<Technology>();
}
[Key]
public string Hostname { get; set; }
public virtual ICollection<Technology> Technologies { get; set; }
}
和
public class Technology
{
[Key, Column(Order = 0)]
public string Name { get; set; }
[Key, Column(Order = 1)]
public string Source { get; set; }
public virtual ICollection<Site> Sites { get; set; }
public Technology()
{
Sites = new HashSet<Site>();
}
}
答案 0 :(得分:0)
您必须检查两个方向:
if(!site.Technologies.Any( o => (o.Name == technology.Name && technology.Source == source)) &&
!technology.Sites.Any(x => x.Hostname == site.Hostname)
)
{
site.Technologies.Add(technology);
technology.Sites.Add(site);
}