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 se开发者_Python百科t; }
[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.
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.
You can read the entity from db and copy the fields. I don't like the approach but when dealing with the similar problems we had to do it.
You never know if the object hasn't been loaded into the context before and if it was you will get an exception when attaching it anyway. At least it is the case for EF but it would be logical for linq for sql too.
精彩评论