开发者

ApplyCurrentValues does not seem to work

开发者 https://www.devze.com 2023-01-29 15:51 出处:网络
I try to do the following with entity framework 4 : public void Update(Site entity) { using (db) { db.Sites.Attach(db.Sites.Single(s => s.Id == entity.Id));

I try to do the following with entity framework 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();
    }
}

But when i try to update a site through this method i get an error telling me that :

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.

And this is because the original site for some reason is not loaded thr开发者_如何学Pythonough the Attach() method.

Can someone help with this ?

/Martin


You don't need to "attach" something you are already retrieving (Ladislav is right). Once you retrieve an entity (e.g SingleOrDefault), it is "in the graph" (EF memory - so it can do optimistic concurrency).

If your trying to do an UPDATE< and the "entity" your passing through is new/detached...

Try the stub technique:

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

That being said, the error you have provided points to some other issue (data conversion).

Have you checked the "date" values you are passing through with the data type on the model?


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();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号