2012-04-04 57 views
0

這是更新代碼,我發現:LINQ到實體更新記錄到數據庫

using (TestDBEntities ctx = new TestDBEntities()) 
{ 
    //Get the specific employee from Database 

    Emp e = (from e1 in ctx.Emp 
     where e1.Name == "Test Employee" 
     select e1).First(); 

    //Change the Employee Name in memory 
    e.Name = "Changed Name"; 

    //Save to database 
    ctx.SaveChanges(); 
} 

現在我在做什麼是這樣的:

using(CRNNSTestEntities crnnsupContext = new CRNNSTestEntities()) 
{ 
    CPersonalInfo t = ((IQueryable<CPersonalInfo>)Cache["personquery"]).First(); 

    t.Tombstone.Address = Address1.Text; 
    System.Windows.Forms.MessageBox.Show(crnnsupContext.SaveChanges()+""); 
}; 

不工作。所以我的問題是我必須寫一些像CPersonalInfo t = from t in ....

爲什麼我的方法不工作?

感謝

回答

0

您需要從Cache

+0

這是否意味着每次我想更新記錄時,我都必須先運行搜索查詢? – pita 2012-04-04 13:12:22

+0

@pita - 是的,您需要從您正在調用的上下文* SaveChanges()*中檢索記錄。 – Aducci 2012-04-04 13:15:30

0

crnnsupContext,並沒有得到實體CPersonalInfo t您也可以前將對象的上下文。

更多信息如何使用附上here

+0

在更新/刪除對象之前將對象附加到上下文是Julia Lerman和Rowan Miller(Microsoft的ADO.NET實體框架團隊的程序經理)在其「編程實體框架:DbContext」第47頁 - http://www.amazon.com/Programming-Entity-Framework-Julia-Lerman/dp/1449312969 – ADIMO 2012-04-06 16:06:31

0

你可以改變這個

using (TestDBEntities ctx = new TestDBEntities()) 
 
{ 
 
    //Get the specific employee from Database 
 

 
    Emp e = (from e1 in ctx.Emp 
 
     where e1.Name == "Test Employee" 
 
     select e1).First(); 
 

 
    //Change the Employee Name in memory 
 
    e.Name = "Changed Name"; 
 

 
    //Save to database 
 
    ctx.SaveChanges(); 
 
}

using (TestDBEntities ctx = new TestDBEntities()) 
 
{ 
 
    //Get the specific employee from Database 
 

 
    Emp e = (from e1 in ctx.Emp 
 
     where e1.Name == "Test Employee" 
 
     select e1).First(); 
 
    var entity = ctx.Emp.Find(e); 
 
    //Change the Employee Name in memory 
 
    entity.Name = "Changed Name"; 
 

 
    //Save to database 
 
    ctx.SaveChanges(); 
 
}