AttachCopy to update existing entity?

3 posts, 1 answers
  1. HHalim
    HHalim avatar
    69 posts
    Member since:
    Aug 2005

    Posted 16 Apr 2013 Link to this post

    How do I update an existing entity using AttachCopy method? Is it possible to do it that way?
    I know I can use the regular update feature, but I'm trying to safe time and effort because some of my entity objects have over 100 fields with data coming in from 3rd party API.

    I've successfully inserted new record using the AttachCopy, but not update an existing record.

    Here is in code of what I'm hoping to do, this doesn't work in updating the existing object:
    public ActionResult Update(UserMeta userMeta)
      {
         var entity = (from u in dbContext.UserMetas
                         where u.UserID == userMeta.userID
                         select u).FirstOrDefault();
          if (entity != null)
          {
               var entity = dbContext.AttachCopy(userMeta);
                   entity.Modified = DateTime.UtcNow;
               dbContext.SaveChanges();
          }
           return View();
    }


    The parameter userMeta object is populated from a form view and has the updated field values. The userMeta class was generated through openaccess database first mapping, so it's the same class definition as entity object.

    Thanks!
  2. Answer
    Yordan
    Admin
    Yordan avatar
    39 posts

    Posted 19 Apr 2013 Link to this post

    Hi Hartono,

    As we see from the provided code the way you use AttachCopy is perfectly fine. However there is a possibility that the entity returned from the query 
    var entity =
    (from u in dbContext.UserMetas
    where u.UserID == userMeta.userID
    select u).FirstOrDefault();
    is null and the rest of the code is not executed. Could you please debug the method and verify that the returned entity is not null. Additionally you could use this version of the Update method:
    public ActionResult Update(UserMeta userMeta)
    {
     if (userMeta != null)
     {
      var attachedUserMeta = dbContext.AttachCopy(userMeta);
      attachedUserMeta.Modified = DateTime.UtcNow;
      dbContext.SaveChanges();
     }
     return View();
    }
    This method will work unless the provided userMeta is null.
    If you encounter any issues using this version of the Update method please do not hesitate to contact us again.
     
    Regards,
    Yordan
    the Telerik team
    Using Encrypted Connection Strings with Telerik OpenAccess ORM. Read our latest blog article >>
  3. DevCraft banner
  4. HHalim
    HHalim avatar
    69 posts
    Member since:
    Aug 2005

    Posted 19 Apr 2013 Link to this post


    From your reply I figured out what the problem was. It's that I don't actually need to manually retrieve the record entity first and then do the AttachCopy. Changing my code and going straight to AttachCopy for insert and update works as intended.

    Thank you!
Back to Top