linq to entity将记录更新到数据库

时间:2012-04-04 12:59:57

标签: asp.net linq entity-framework linq-to-entities

这是我找到的更新代码:

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 ....

这样的东西

为什么我的方法不起作用?

谢谢

3 个答案:

答案 0 :(得分:0)

您需要从CPersonalInfo t而不是crnnsupContext

获取实体Cache

答案 1 :(得分:0)

您也可以在之前将对象附加到上下文。

更多信息如何使用附件here

答案 2 :(得分: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();
}