我的领域课程:
public class Address
{
[Key]
public virtual string AddressId { get; set; }
public virtual Site Site { get; set; }
}
public class Site
{
[Key]
public virtual int SiteId { get; set; }
public virtual Address Address { get; set; }
}
使用 Fluent API 进行映射:
public class SiteMappings : EntityTypeConfiguration<Site>
{
public SiteMappings()
{
HasRequired(s => s.Address)
.WithOptional(a => a.Site)
.Map(s => s.MapKey("AddressId"))
.WillCascadeOnDelete(false);
}
}
种子方法:
var addresses = new List<Address>
{
new Address { AddressId = "1" }
};
addresses.ForEach(s => context.Addresses.AddOrUpdate(p => p.AddressId, s));
var sites = new List<Site>
{
new Site { SiteId = 1, Address = addresses.Single(s => s.AddressId.Equals("1"))}
};
sites.ForEach(s => context.Sites.AddOrUpdate(p => p.SiteId, s));
错误:
Violation of PRIMARY KEY constraint 'PK_dbo.Addresses'. Cannot insert duplicate key in object 'dbo.Addresses'. The duplicate key value is (1)
似乎是当我尝试添加一个新的“站点”时,新的“地址”也会被插入。如何避免这种情况?如何在我之前添加的 DBcontext 中插入现有的“地址”。我是 Entity Framework 的新手,非常感谢您的帮助。提前致谢!