ApplyCurrentValues似乎不起作用

时间:2010-12-08 07:22:21

标签: entity-framework entity-framework-4

我尝试使用实体框架4执行以下操作:

public void Update(Site entity)
{
    using (db)
    {
        db.Sites.Attach(db.Sites.Single(s => s.Id == entity.Id));
        db.Sites.ApplyCurrentValues(entity);
        db.SaveChanges();
    }
}

但是当我尝试通过这种方法更新网站时,我得到一个错误告诉我:

  

datetime2数据的转换   输入到日期时间数据类型   在超出范围的价值。该   声明已被终止。

这是因为原因网站由于某种原因没有通过Attach()方法加载。

有人可以帮忙吗?

/马丁

2 个答案:

答案 0 :(得分:3)

你不需要“附加”你正在检索的东西(Ladislav是对的)。一旦你检索到一个实体(例如SingleOrDefault),它就是“在图中”(EF内存 - 所以它可以做到乐观的并发)。

如果您尝试进行更新<你经过的“实体”是新的/分离的......

尝试使用存根技术

public void Update(Site entity)
{
    using (db)
    {
        var stub = new Site { Id = entity.Id }; // create stub with given key
        db.Sites.Attach(stub); // stub is now in graph
        db.Sites.ApplyCurrentValues(entity); // override graph (stub) with entity
        db.SaveChanges();
    }
}

话虽如此,您提供的错误指向其他一些问题(数据转换)。

您是否使用模型上的数据类型检查了您所经过的“日期”值?

答案 1 :(得分:0)

public ActionResult Edit(int id, Client collection)
{
   try
   {
      // make sure the rec is in the context
      var rec = dbEntities.Clients.First(r => r.ClientID == id);  
      // update the rec in the context with the parm values
      dbEntities.Clients.ApplyCurrentValues(collection);          
      // make the changes permanent
      dbEntities.SaveChanges();                                   
      return RedirectToAction("Index");
    }
    catch
    {
      return View();
    }
}
相关问题