Dapper UpdateAsync 忽略列

Dapper UpdateAsync ignore column

我正在尝试用 Dapper.Contrib 更新这个 table:

public class MyTable
{
    public int ID { get; set; }
    public int SomeColumn1 { get; set; }
    public int SomeColumn2 { get; set; }
    public int CreateUserID { get; set; }
    public int UpdateUserID { get; set; }
}

我不想更新 CreateUserID 列,因为它是一种更新方法,因此我想在调用 Dapper - Update.Async(entity) 方法时忽略此列。

我尝试使用 [NotMapped] 和 [UpdateIgnore] 属性但没有帮助。

注意:我仍然希望在插入操作时传递此列,因此,[Computed] 和 [Write(false)] 不合适。

谁能帮我弄清楚如何在更新数据库中的 table 时忽略此列?

我建议使用 [Computed] 属性。

[Computed] - this property is computed and should not be part of updates

但是,Dapper.Contrib 的文档似乎措辞混乱。 [Computed] 属性在插入时似乎也被忽略了 - 这可能适用于您的用例,也可能不适用于您的用例。

嗯,只是不支持。这里是相关的issue, and solution is expected only in Dapper v2. You can also inspect source code(很简单),看到更新的属性搜索如下:

 var allProperties = TypePropertiesCache(type);
 keyProperties.AddRange(explicitKeyProperties);
 var computedProperties = ComputedPropertiesCache(type);
 var nonIdProps = allProperties.Except(keyProperties.Union(computedProperties)).ToList();

因此所有未标记 Key\ExplicitKey\Computed 且可写的属性都包括在内。 InsertAsync也是如此(除了带有ExplicitKey的属性也包含在insert中,但是你不能在你的情况下使用这个属性,因为你的属性毕竟不是key)。

所以你必须等待它被实现,自己分叉和实现,或者只写你自己的 UpdateAsync 方法。从源码可以看出非常简单,重新实现起来也不难。

正如@Evk 在他的回答中已经提到的那样,目前还没有实施任何解决方案。他还提到了解决方法。

除此之外,对于这种特殊情况,您可以选择直接绕过 Dapper.Contrib 使用 Dapper (IDbConnection.Execute(...))。

我有一个类似的问题(虽然有 DapperExtensions),关于特定的列更新和其他复杂的查询,这些 DapperExtensions 要么根本无法生成,要么需要做很多工作才能实现。

对于那个特定的案例,我直接使用了 Dapper 而不是 DapperExtensions;项目的其他部分仍然利用 DapperExtensions。这就像踩踏。这种情况非常有限。我发现这是更好的解决方案,而不是 tweaking/forcing DapperExtensions。这也节省了我的时间和精力。