更新检查使用 DataContext Attach 方法更新实体时出现问题
我正在尝试在通用存储库中创建一个更新方法作为 LINQ to SQL 数据访问层。
我有一个像这样的实体:
[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; }
....
}
我为除 id 之外的所有字段设置 Update Check = true
正如 @jeff Atwood 在 这篇文章,我将 Attach 方法中的 asModified
属性设置为 true,这是我发现的在 这篇文章如下:
public void Update(T entity)
{
_db.GetTable<T>().Attach(entity, true);
_db.SubmitChanges();
}
但我不断收到相同的异常:
如果满足以下条件,实体只能以修改后的状态(没有原始状态)附加: 它声明了版本成员或没有更新检查策略。
那么问题出在哪里呢???
除了创建时间戳列作为版本号之外,您是否建议使用任何其他方法在通用存储库中创建更新方法。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我们在 DAO 中使用以下代码来解决相同的问题:
(例如,目前我身上没有真正的代码)
ReadOnlyDataContext has TrackChanges = false;
我们无法根据我们的需求找到另一种解决方案,而不必编写大量的管道代码。
我们也无法修改数据库来满足 LinqToSql 对 timestamp 列的需求。
在我们的测试中,额外的数据库调用没有造成任何问题。
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)
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.
您可以从数据库读取实体并复制字段。我不喜欢这种方法,但在处理类似的问题时我们不得不这样做。
您永远不知道该对象之前是否尚未加载到上下文中,如果是的话,无论如何在附加它时都会出现异常。至少 EF 是这样,但对于 linq for sql 来说也是合乎逻辑的。
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.