我有两个实体,定义如下
public class Corporation
{
public int Id{get;set;}
public string Name{get;set;}
public List<Location> Locations{get;set;} // All locations under this corp
}
public class Location
{
public int Id{get;set;}
public Corporation Corporation{get;set;} // Corporation is required in configuraion
}
当我尝试添加一个公司和一个位置时,会定义两个公司。一个是我的添加公司函数定义的(这很好),另一个是添加位置函数定义的(这是问题所在)。
添加位置函数如下:
public void AddLocation(int locationId)
{
using (Context context = new Context())
{
Location location = new Location();
location.Corporation = GetCorporationFromDb(corpId);
context.Locations.Add(location); // This one adds another same Corporation to DB
context.SaveChanges();
}
}
我该如何避免这种情况?我必须在位置之前添加公司名称,因为在实现中,位置使用公司的数据库ID计算电子代码。
DbContext
并将其传递给AddLocation
和AddCorporation
方法的方法。 - Jesse van AssenCorporation.HasMany()
和Location.HasRequired()
),我从来没有遇到你描述的问题。你也可以像@RicoSuter建议的那样将实体附加到上下文中,如此处所示,但我对该方法没有经验,所以无法给出建议。 - Jesse van Assen