加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用DataContext Attach方法更新实体时更新检查’问题

发布时间:2020-12-15 17:20:45 所属栏目:百科 来源:网络整理
导读:我正在尝试在通用存储库中创建一个更新方法作为LINQ to SQL数据访问层. 我有这样一个实体: [Table]public class Product{ [Column(IsPrimaryKey = true,IsDbGenerated = true,DbType = "Int NOT NULL IDENTITY")] public int Id { get; private set; } [Col
我正在尝试在通用存储库中创建一个更新方法作为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在this post中建议我将attach方法中的asModified属性设置为true,我在this post中找到如下:

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

但我一直得到同样的例外:

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.

所以有什么问题 ???

除了将时间戳列创建为版本号之外,是否建议使用任何其他方法在通用存储库中创建更新方法.

解决方法

我们在DAO中使用以下代码来解决相同的问题:
(例如,目前没有真正的代码)

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

ReadOnlyDataContext具有TrackChanges = false;

我们无法根据我们的需求找到另一种解决方案,而无需编写大量的管道代码.
修改数据库以适应LinqToSql对时间戳列的需求对我们来说也不是一个选择.

额外的DB调用在我们的测试中没有产生任何问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读