这是我的示例代码
class Sample
{
public int Id{ get;set; }
public int AssociatedSiteId { get; set; }
[ForeignKey("AssociatedSiteId")]
public virtual SiteA Site { get; set; }
[ForeignKey("AssociatedSiteId")]
public virtual SiteB SiteB { get; set; }
}
I m Inserting the data as
using (var dbcontext = new sampleEntities)
{
var sample = new Sample();
sample.Id=1;
sample.AssociateId = siteInfo.SiteId; // This Id from SiteA Table
dbcontext.Sample.Add(sample);
dbcontext.SaveChanges();
}
我尝试将数据插入到样本中,我得到的错误为:
INSERT语句与FOREIGN KEY约束冲突。
我是EF新手可以请任何人帮助我吗?
答案 0 :(得分:0)
我假设您需要一些指导:)
我有一个问题:为什么Site和SiteB使用相同的外键变量?他们不是不同的实体吗? (SiteA和SiteB)
如果你有
Sample.SiteA => MySiteA
Sample.SiteB => MySiteB
they cannot use the same foreignh key. Even if they are the same type, that key is used to locate the foreign entity and you would be overwriting one with the another... Check your code with mine.
尝试以下方法:
class Sample
{
public int Id{ get;set; }
public int AssociatedSiteAId { get; set; } // Optional but sometimes useful if you don't use [ForegnKey("...")]
[ForeignKey("AssociatedSiteAId")]
public virtual SiteA Site { get; set; }
public int AssociatedSiteBId { get; set; } // Optional but sometimes useful if you don't use [ForegnKey("...")]
[ForeignKey("AssociatedSiteBId")]
public virtual SiteB SiteB { get; set; }
}
在你的代码上,
using (db = new DbContext())
{
var site_a = db.SitesA.Find(123); // 1 should be the key of site a
var site_b = db.SitesB.Find(456); // 2 should be the key of site b
Sample sample = new Sample()
{
SiteA = site_a,
SiteB = site_b
};
db.Samples.Add(sample);
db.SaveChanges();
}