实体框架增加了新的记录导航属性
问题描述:
我有两个实体,定义如下实体框架增加了新的记录导航属性
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计算电子代码。
答
如果您从与您用来添加位置的数据不同的数据上下文中获取公司,就会发生这种情况。尝试:
Context context = new Context();
Location location = new Location();
Corporation corporation = context.Corporations
.Where(x => x.Id == corpId)
.First();
location.Corporation = corporation;
context.Locations.Add(location);
context.SaveChanges();
这样,您使用相同的上下文检索Corporation
并添加Location
。
它也可能附加从另一个上下文加载到新的上下文中的对象... – 2012-03-31 14:33:21
这可能是问题的原因。我会尝试你上班时的建议。 – 2012-03-31 19:03:15
我想在一个单独的方法中添加位置。我是否应该将上下文作为参数传递给该函数并添加该位置?将上下文传递给另一个方法是否会导致问题? – 2012-04-02 06:51:34