实体框架添加了导航属性的新记录

Mer*_*aya 2 .net c# database entity-framework

我有两个实体,定义如下

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
}
Run Code Online (Sandbox Code Playgroud)

当我尝试添加公司然后添加位置时,我会定义两个公司.一个通过我的功能添加公司(这很好),一个通过添加位置的功能(这是问题).

位置添加功能如下:

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();
     }
}
Run Code Online (Sandbox Code Playgroud)

我怎么能避免这个?我必须在Location之前添加公司,因为在实施中,Location使用公司的数据库Id计算电子代码.

Jes*_*sen 7

如果您从与用于添加位置的数据上下文不同的数据上下文中获取公司,则会发生这种情况.尝试:

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();
Run Code Online (Sandbox Code Playgroud)

这样,您使用相同的上下文来检索Corporation和添加Location.