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

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

问题描述

期望建立一个框架(没有存储库模式可直接与DbSets一起使用)以自动填充Created和Last修改,而不是通过代码库散布这些代码。

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
进行抽查时,更改跟踪都会将该实体标记为已修改。

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:


新的已跟踪和<$ c ChangeTracker 上的$ c> 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 构造函数

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中自动填充创建和LastModified的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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