c#-实体框架-在种子方法中将现有实体添加到一对一关系
作者:互联网
我的网域类别:
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的新手,非常感谢您的帮助.
提前致谢!
解决方法:
将地址分配给站点实例后,将其用于每个地址实例:
context.Entry(existingAddress).State = EntityState.Unchanged;
这会将地址的状态设置为“未更改”,而不是“已添加”,并且EF不会尝试再次添加它们.
还可以尝试在添加地址的ForEach之后调用context.SaveChanges().
标签:ef-fluent-api,ef-migrations,dbcontext,c,entity-framework 来源: https://codeday.me/bug/20191121/2051832.html