Search code examples
c#linq-to-sqlupdatecheck

Update check' issue when updating an entity using DataContext Attach method


I'm trying to create an update method in a generic repository as a LINQ to SQL data access layer.

I have an entity like this:

[Table]
public class Product
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true, 
     DbType = "Int NOT NULL IDENTITY")]
    public int Id { get; private set; }
    [Column(UpdateCheck = UpdateCheck.Never)]
    public string Name { get; set; }
    ....
}

I set Update Check = true for all the fields exept for the id as @jeff Atwood suggests in this post and I set the asModified propery in the attach method to true which i found in this post as following:

public void Update(T entity)
{
    _db.GetTable<T>().Attach(entity, true); 
    _db.SubmitChanges();
}

but I keep getting the same exception:

An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.

So what's the problem ???

Do you recommend any other approaches to create an update method in a generic repository except creating a timestamp column as a version number.


Solution

  • We used the following code in our DAO to solve the same issue:
    (e.g. only, don't have the real code on me at the moment)

    public void UpdateUser(tblUser user)
    {
       WriteDataContect.Attach
       (
          user,
          ReadOnlyDataContext.tblUsers
                             .Select(o => o.UserId == user.UserId)
       );
       WriteDataContext.SubmitChanges();
    }
    

    ReadOnlyDataContext has TrackChanges = false;

    We couldn't find another solution based on our needs, without having to write alot of plumbing code. Modifying the database to accommodate LinqToSql's need for a timestamp column wasn't an option for us either.

    The additional DB call didn't create any issues in our testing.