On Insert / Update logic in EF code first

前端 未结 2 522
时光说笑
时光说笑 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: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();
        }
    

提交回复
热议问题