在 EF Core 中自动填充 Created 和 LastModified [英] Populate Created and LastModified automagically in EF Core

查看:35
本文介绍了在 EF Core 中自动填充 Created 和 LastModified的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

期待构建一个框架,(没有直接使用 DbSet 的存储库模式)自动填充 Created 和 last modified ,而不是通过代码库吐出这些代码.

Looking forward to build a framework, (No repository pattern to working with DbSets directly) to autopopulate Created and last modified automatically, rather than spitting out these codes through out code base.

你能指出我正确的方向如何实现它.

Could you point me out in right direction how to achieve it.

过去我尝试在构造函数中填充这些,但是这似乎就像一个讨厌的代码,每次我们从数据库 EF 中提取 somting更改跟踪会将实体标记为已修改.

In past I tried populating these in constructors, however that seems like a nasty code and every time we pull up somting from database EF change tracking will mark the entity as modified.

.ctor()
    {
        Created = DateTime.Now;
        LastModified = DateTime.Now;
    }

public interface IHasCreationLastModified
    {
        DateTime Created { get; set; }
        DateTime? LastModified { get; set; }
    }

public class Account : IEntity, IHasCreationLastModified
{
    public long Id { get; set; }

    public DateTime Created { get; set; }
    public DateTime? LastModified { get; set; }
    public virtual IdentityUser IdentityUser { get; set; }
}

推荐答案

从 v2.1 开始,EF Core 提供 状态变化事件:

Starting with v2.1, EF Core provides State change events:

New TrackedChangeTracker 上的 StateChanged 事件可用于编写对进入 DbContext 或改变他们的状态.

New Tracked And StateChanged events on ChangeTracker can be used to write logic that reacts to entities entering the DbContext or changing their state.

您可以从 DbContext 构造函数内部订阅这些事件

You can subscribe to these events from inside your DbContext constructor

ChangeTracker.Tracked += OnEntityTracked;
ChangeTracker.StateChanged += OnEntityStateChanged;

然后做这样的事情:

void OnEntityTracked(object sender, EntityTrackedEventArgs e)
{
    if (!e.FromQuery && e.Entry.State == EntityState.Added && e.Entry.Entity is IHasCreationLastModified entity)
        entity.Created = DateTime.Now;
}

void OnEntityStateChanged(object sender, EntityStateChangedEventArgs e)
{
    if (e.NewState == EntityState.Modified && e.Entry.Entity is IHasCreationLastModified entity)
        entity.LastModified = DateTime.Now;
}

这篇关于在 EF Core 中自动填充 Created 和 LastModified的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆