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