我的领域类:
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不熟悉,非常感谢您的帮助。 提前致谢!
new Site { SiteId = 1, Address = context.Addresses.FirstOrDefault(a => a.AddressId.Equals("1"))}
- Para Kan