簡體   English   中英

如何檢測 Entity Framework Core 2.x 中特定實體的屬性更改?

[英]How can I detect changes to properties in a specific entity in Entity Framework Core 2.x?

當用戶保存對對象myObject更改時,我想記錄更新到該對象的字段。

我可以得到一個對象

var myObject = await context.MyObjects.SingleAsync(x => x.Id == id);

我看到我可以得到一個IEnumerable<PropertyEntry>

var changes = context.Entry(myObject).Properties.Where(x => x.IsModified);

但是在我的changes列表中,我在任何地方都看不到字段名稱。 此外,在 LINQPad 中使這個成員查詢似乎需要整整 2 秒。 這似乎不對。

我如何完成以下陳述?

Consolse.Write($"The field {what goes here?} was updated from {change.OriginalValue} to {change.CurrentCalue}.");

我發現的其他 StackOverflow 問題是針對以前版本的實體框架,或者覆蓋SaveChanges並且不查找特定實體。

更新! 知道了。

public string GetChangeLog<T>(
    ApplicationDbContext context,
    T entity)
{
    var sb = new StringBuilder();

    var changes = context.Entry(entity).Properties.Where(x => x.IsModified);

    foreach (var change in changes)
    {
        var propertyBase = (IPropertyBase)change.Metadata;
        sb.Append($"\"{propertyBase.Name}\" was changed from \"{change.OriginalValue}\" to \"{change.CurrentValue}\"\n");
    }

    return sb.ToString();
}

使用.Metadata屬性來檢索IPropertyBase 這將告訴您實際發生了什么變化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM