2015-02-12 139 views
2

嗨,我在我的代碼中遇到問題。無法更新數據庫實體

public static void settingSoundxStringLawyers_info() 
     { 

      mydatabaseEntities db2 = new mydatabaseEntities(); 

      var UniqueNameObjects = from a in db2.Lawyers_info 
            group a by a.Name into g 
            where g.Count()==1 
            select new Names { Name = g.Key }; 

      List<Names> list = UniqueNameObjects.ToList(); 
      for (int i=0; i<150 ; i++) 
      { 
       string name = list.ElementAt(i).Name; 
       Lawyers_info obj = db2.Lawyers_info.Where(l => l.Name == name).First(); 


       string scode = soundxmethod(obj.Name); 
       obj.SoundxString = scode; 
       db2.Entry(obj).State = EntityState.Modified; 
       //var dbEntityEntry = db2.Entry(obj); 
       //dbEntityEntry.Property(s=>s.SoundxString).IsModified = true; 

       Console.WriteLine("Index: ----> "+(i+1)); 
       //db2.Lawyers_info.Add(obj); 

       //db2.Set(Lawyers_info).SqlQuery("update Lawyers_info values(SoundxString = @p)",new sq) 
       db2.SaveChanges(); 
      } 
      db2.SaveChanges(); 
     } 

我試過每個註釋行但不是woking。更改不會保存在數據庫中。

回答

0

由於您正在從數據庫中獲取「Lawyers_info」實體,所以在更改屬性(不需要設置EntityState.Modified)後,它的狀態將爲Modified。

另外你只需要調用一次SaveChanges()。在修改實體之後,或者在修改全部150之後,或者兩者都不是。

另外請確保獲取受SaveChanges影響的行(它返回一個int)。通過這種方式,您可以分辨出哪些行已被更新。 HTH