我可以建立一个通用的更新操作吗?

本文关键字:更新 操作 一个 建立 我可以 | 更新日期: 2023-09-27 18:08:43

对于我的每个表都有键值,所以我的问题是如何获得键属性?我想搜索参数中得到的对象并通过更新后的对象更新表。我如何从表中找到我的对象?

public static void Update<TEntity>(TEntity UpdatedObject) where TEntity : class
        {
            DatabaseLinqDataContext ClientLinq = new DatabaseLinqDataContext(Patch);
            ClientLinq.GetTable<TEntity>()// I want to search that object i got in the paramater and update it. how do I find my object from the table?
            ClientLinq.SubmitChanges();
        }

任何想法?解决这个问题的正确方法是什么?

此操作写入业务逻辑层。

我可以建立一个通用的更新操作吗?

有几个情况需要考虑。

如果实体实例以前是由这个数据上下文加载的,只需调用SubmitChanges。不需要做任何其他事情(此时所有修改的实例都将被更新)。

如果实体实例以前是由不同的数据上下文加载的,则需要创建一个不会被跟踪的新副本,然后执行下一个情况。

如果实体实例不是由数据上下文加载的(或者该实例是上面的副本),那么您需要调用

  //attach the changes to the tracked object graph
dataContext.GetTable<T>().Attach(t, true);
  //if type uses optimistic concurrency, then you need to refresh
  //load the "original" state for the tracked object graph
dataContext.Refresh(t, RefreshMode.KeepCurrentValues);
dataContext.SubmitChanges();

或者,最好调用:

dataContext.GetTable<T>().Attach(tChanged, tOriginal);
dataContext.SubmitChanges();