本文介绍了在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.



.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:

您可以从 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 22:46