简体   繁体   中英

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.

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. I want to create the ProductsStatus table.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM