在EF Core中自动填充创建和LastModified [英] Populate Created and LastModified automagically in EF Core
问题描述
期望建立一个框架(没有存储库模式可直接与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:
新的
已跟踪
和<$ cChangeTracker
上的$ c> StateChanged 事件可用于编写对进入DbContext $ c的实体做出反应的逻辑$ c>或更改其状态。
New
Tracked
AndStateChanged
events onChangeTracker
can be used to write logic that reacts to entities entering theDbContext
or changing their state.
您可以从 DbContext $内部订阅这些事件。 c $ c>构造函数
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屋!