2013-05-08 93 views
0

我有以下提到的2個模型。實體框架模型屬性沒有正確更新

GeoLocation中型號:

public class GeoLocation { 
     public GeoLocation() { } 
     public int Id { get; set; } 
     public double Latitude { get; set; } 
     public double Longitude { get; set; } 
    } 

提供商型號:

public class Provider 
    { 
     public Provider() 
     { 
      Id = Guid.NewGuid(); 
      Created = DateTime.Now; 
     } 

     public Guid Id { get; set; } 
     [Required] 
     public string Name { get; set; } 

     public virtual GeoLocation Location { get; set; } 

    } 

方法:

public void SetLocation(string providerKey, GeoLocation location) 
     { 
      var provider = (from p in Catalog.Providers 
          where p.Key == providerKey 
          select p).Single(); 

      provider.Location = location; 

      Catalog.SaveChanges(); 
} 

像上面我需要更新提供商表的位置對象。但上面的代碼給出奇怪的結果。那就是當傳入位置對象具有Id讓我們說15.那麼我需要更新該ID到供應商表位置Id .But上面的代碼後,它更新爲16不是15.你能告訴我爲什麼?這裏的根本問題是什麼?

注:我正在使用默認的EF約定映射。

更新:我已經找到了問題here.That是,當我把provider.Location = location;GeoLocation中自動遞增編號增加1。那是cause.So我怎麼能避免呢?

回答

1

你是如何得到位置的?問題是你的EF上下文(Catalog)認爲該位置是一個新的對象要被持久化(=它生成插入位置表)。您必須通知目錄它已經存在的對象。

這可能使一招:

if (location.Id > 0) { 
    Catalog.GeoLocations.Attach(location); 
} 

provider.Location = location; 
+0

感謝lot.This幫助了我。 – Sampath 2013-05-09 12:27:55

+0

您能否給予任何支持:http://stackoverflow.com/questions/18364476/entity-object-cannot-be-referenced-by-multiple-instances-of-ientitychangetracker?noredirect = 1#comment26965112_18364476 – Sampath 2013-08-21 19:27:06