Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

entity framework - On Insert / Update logic in EF code first

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 version of the name property.

public class Category
{

    public string Name { get; set; }
    public string UrlName{ get; set; }
}

I would like to set the UrlName property only on the insert and update events because my slugify logic is quite elaborate.

I am aware that I can add some logic inside the SaveChanges() function on the context itself but I rather would like to put the code closer to the entity itself.

Is there a way to accomplish such thing using EF code first?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...