2012-03-31 55 views
2

我有兩個實體,定義如下實體框架增加了新的記錄導航屬性

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計算電子代碼。

回答

6

如果您從與您用來添加位置的數據不同的數據上下文中獲取公司,就會發生這種情況。嘗試:

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

+0

它也可能附加從另一個上下文加載到新的上下文中的對象... – 2012-03-31 14:33:21

+0

這可能是問題的原因。我會嘗試你上班時的建議。 – 2012-03-31 19:03:15

+0

我想在一個單獨的方法中添加位置。我是否應該將上下文作爲參數傳遞給該函數並添加該位置?將上下文傳遞給另一個方法是否會導致問題? – 2012-04-02 06:51:34