简体   繁体   English

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

[英]Entity Framework adds new record for navigation property

I have two entities, defined as following 我有两个实体,定义如下

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
}

When I try to add a Corporation and then a location, I get two Corporation defined. 当我尝试添加公司然后添加位置时,我定义了两个公司。 One by my function that adds Corporation(which is fine), and one by the function that adds location(which is the issue). 一种是通过我的功能添加Corporation(很好),另一种是通过功能添加位置(这就是问题)。

Location adding function is like this: 位置添加功能如下:

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();
     }
}

How can I avoid this? 我怎么能避免这个? I have to add Corporation before Location because in the implementation Location calculates an electronic code using Corporation's database Id. 我必须在“位置”之前添加“公司”,因为在实现中,“位置”使用“公司”的数据库ID计算电子代码。

This happens if you fetch the corporation from a different data context than the one you use to add the location. 如果您从不同于用于添加位置的数据上下文中获取公司,则会发生这种情况。 Try: 尝试:

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();

This way, you use the same context for retrieving the Corporation and adding the Location . 这样,您可以使用相同的上下文来检索Corporation并添加Location

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM