在EF代码中首先插入/更新逻辑 [英] On Insert / Update logic in EF code first

查看:115
本文介绍了在EF代码中首先插入/更新逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加一些逻辑来插入和更新一些EF对象的事件。
我有一个具有类别对象的MVC应用程序,该对象具有一个属性,该属性是name属性的slugified版本。

  public class Category 
{

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

我只想在插入和更新事件时设置UrlName属性因为我的逻辑逻辑是非常精细的。



我知道我可以在上下文本身的SaveChanges()函数中添加一些逻辑,但我宁愿把代码更靠近实体本身。



有没有办法使用EF代码来完成这样的事情?

解决方案

您可以使用插入和更新前调用的方法设置基类

  public abstract class Entity 
{
public virtual void OnBeforeInsert(){}
public virtual void OnBeforeUpdate(){}
}

public class类别:Entity
{

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

public override void OnBeforeInsert()
{
// ur logic
}
}
/ pre>

然后在您的 DbContext

  public override int SaveChanges()
{
var changedEntities = ChangeTracker.Entries();

foreach(var changedEntity in changedEntities)
{
if(changedEntity.Entity是Entity)
{
var entity =(Entity)changedEntity.Entity ;

switch(changedEntity.State)
{
case EntityState.Added:
entity.OnBeforeInsert();
break;

case EntityState.Modified:
entity.OnBeforeUpdate();
break;

}
}
}

return base.SaveChanges();
}


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?

解决方案

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

这篇关于在EF代码中首先插入/更新逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆