[英]How to emulate a SQL trigger in Entity Framework Core (code first)?
Entity Framework does not support triggers.实体框架不支持触发器。 Is there something that reproduces their behavior?
有什么东西可以复制他们的行为吗?
I'm not interested in inserting SQL queries in my code.我对在我的代码中插入 SQL 查询不感兴趣。
I have this question because I have a case which I want to create a new table on my database that will be filled with information whenever something is inserted in another existing table.我有这个问题,因为我有一个案例,我想在我的数据库中创建一个新表,只要在另一个现有表中插入内容,该表就会填充信息。
Like this:像这样:
Suppose I have a Prodcuts
table.假设我有一个
Prodcuts
表。 I want to create the ProductsStatus
table.我想创建
ProductsStatus
表。
If something is inserted into the Products
table, I want to add a record to the ProductStatus
table, storing the ProductId
(foreign key), a DateTime
column and a Stored
status for this product.如果将某些内容插入到
Products
表中,我想向ProductStatus
表中添加一条记录,存储该ProductId
(外键)、一个DateTime
列和一个Stored
状态。
The point is to avoid refactoring every place where I add a product on my code in order to do this new operation.关键是要避免重构我在代码上添加产品的每个地方,以便执行此新操作。
I do something like this in some of my contexts:我在某些情况下会做这样的事情:
public partial class XContext : DbContext
{
private void TrackDates()
{
foreach (var entityEntry in ChangeTracker.Entries())
{
if (entityEntry.Entity is BaseEntity be)
{
switch (entityEntry.State)
{
case EntityState.Deleted: //soft delete instead
entityEntry.State = EntityState.Modified;
be.DeletedDate = DateTime.UtcNow;
break;
case EntityState.Modified:
be.ModifiedDate = DateTime.UtcNow;
be.CreatedDate = DateTime.UtcNow;
break;
case EntityState.Added:
be.CreatedDate = DateTime.UtcNow;
break;
}
}
}
}
public override int SaveChanges()
{
TrackDates();
return base.SaveChanges();
}
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
{
TrackDates();
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
}
Every time SaveChanges is called it updates the UpdatedDate, or marks an DeletedDate to make soft delete etc, which is "kind of like what some triggers do sometimes".. Perhaps you can extend it to do some of your needs..每次调用 SaveChanges 时,它都会更新 UpdatedDate,或者标记一个 DeletedDate 以进行软删除等,这“有点像某些触发器有时会做的事情”.. 也许您可以扩展它来满足您的一些需求..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.