On Insert / Update logic in EF code first

前端 未结 2 521
时光说笑
时光说笑 2020-12-09 10:59

I would like to add some logic to the insert and update events of some EF objects. I have a MVC application with category object which has a property which is a slugified ve

相关标签:
2条回答
  • 2020-12-09 11:15

    No there is no such extension point because your entity is POCO - it is not aware of its persistence. Such logic must be triggered in data access layer which is aware of persistence. DbContext API offers only overriding of SaveChanges.

    You can expose custom events or methods on your entities and call them during processing in SaveChanges.

    0 讨论(0)
  • 2020-12-09 11:20

    You can setup a base class with methods to be called before insert and update

    public abstract class Entity
    {
        public virtual void OnBeforeInsert(){}
        public virtual void OnBeforeUpdate(){}
    }
    
    public class Category : Entity
    {
    
        public string Name { get; set; }
        public string UrlName{ get; set; }
    
        public override void OnBeforeInsert()
        {
           //ur logic
        }
    }
    

    Then in your DbContext

        public override int SaveChanges()
        {
            var changedEntities = ChangeTracker.Entries();
    
            foreach (var changedEntity in changedEntities)
            {
                if (changedEntity.Entity is Entity)
                {
                    var entity = (Entity)changedEntity.Entity;
    
                    switch (changedEntity.State)
                    {
                        case EntityState.Added:
                            entity.OnBeforeInsert();
                            break;
    
                        case EntityState.Modified:
                            entity.OnBeforeUpdate();
                            break;
    
                    }
                }
            }
    
            return base.SaveChanges();
        }
    
    0 讨论(0)
提交回复
热议问题