问题描述
期待构建一个框架,(没有直接使用 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更改跟踪会将实体标记为已修改.
.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 Tracked
和 ChangeTracker
上的 StateChanged
事件可用于编写对进入 DbContext
或改变他们的状态.
您可以从 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!