EF Code First: Join table is empty
I have two Entity Framework Code First POCOs. I can insert new Site and Technology items into the database easily, but I can't seem to associate Sites with Technologies. When I do this ...
if(!site.Technologies.Any( o => (o.Name == technology.Name && technology.Source == source)))
{
site.Technologies.Add(technology);
technology.Sites.Add(site);
}
I get a duplicate key error. If I remove the second line from the conditional, the join table TechnologiesSites does not get any records! How do I do an insert in 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; }
}
and
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>();
}
}
You have to check both directions:
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);
}
精彩评论