【问题标题】:in Entity framework, how to call a method on Entity before saving在实体框架中,如何在保存之前调用实体上的方法
【发布时间】:2011-07-13 10:00:48
【问题描述】:

下面我创建了一个演示实体来演示我在寻找什么:

public class User :  IValidatableObject
{
    public string Name { get; set; }

    [Required]
    public DateTime CreationDate { get; set; }

    public DateTime UpdatedOnDate { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if(Name = "abc")
        {
            yield return new ValidationResult("please choose any other name then abc", new[] { "Name" });
        }
    }
}

我正在实现IValidatableObject 接口来使这个实体自我验证。

现在正在创建新用户我正在这样做

User u = new User();
u.Name = "Some name";
u.CreationDate = DateTime.Now
dbContext.Users.Add(u);
dbContext.SaveChanges();

我计划将u.CreationDate=DateTime.Now; 代码转移到User 类中。并实现一个接口,该接口提供一个方法,该方法将在保存之前和验证之后执行

// class structure that I am looking for
public class User : IValidatableObject,IMyCustomInterFace
{
    //rest codes as above class

    public void MyMethod(Whatever)
    {
        //this method gets called after Validate() and before save

        if(dataContext.Entry<User>(this).State == System.Data.EntityState.Added)
        {
            //add creation date_time
            this.CreationDate=DateTime.Now;

            //SET MORE DEFAULTS
        }

        if(dataContext.Entry<User>(this).State == System.Data.EntityState.Modified)
        {
            //update Updation time
            this.UpdatedOnDate = DateTime.Now;
        }
    }
}

现在要创建一个新用户,我只需要按以下方式进行操作,注意我这次没有添加日期属性,Class 会自动添加。

User u = new User();
u.Name = "Some name";
dbContext.Users.Add(u);
dbContext.SaveChanges();

更新用户,UpdatedOnDate 属性将按类自动更新

User u = getUserFromSomeWhere();
u.Name = "Updated Name";
dataContext.Entry<User>(u).State = System.Data.EntityState.Modified;
dbContext.SaveChanges();

我的问题:是否有任何现有的界面提供 在SaveAfterValidate 之前调用的某些方法或其他一些我可能不知道的方法。

或者,如果我创建了我的自定义接口,我怎样才能让它的方法按照我想要的顺序执行。

【问题讨论】:

标签: c# entity-framework ef-code-first entity-framework-4.1


【解决方案1】:

我有一个几乎相同的情况,我通过处理上下文中的SavingChanges 事件来管理它。

首先我创建一个定义时间戳操作的接口:

public interface IHasTimeStamp
{
    void DoTimeStamp();
}

然后我在我的实体中实现这个接口:

Public class User : IHasTimeStamp
(
    public void DoTimeStamp()
    {
        if(dataContext.Entry<User>(this).State == System.Data.EntityState.Added)        
        {            
            //add creation date_time            
            this.CreationDate=DateTime.Now;            
        }        

        if(dataContext.Entry<User>(this).State == System.Data.EntityState.Modified)        
        {            
            //update Updation time            
            this.UpdatedOnDate=DateTime.Now;        
        }
    }
}

最后一步是注册 SavingChanges 处理程序并实现它。

public partial class MyEntities
{
    partial void OnContextCreated()
    {
        // Register the handler for the SavingChanges event.
        this.SavingChanges
            += new EventHandler(context_SavingChanges);
    }

    // SavingChanges event handler.
    private static void context_SavingChanges(object sender, EventArgs e)
    {
        // Validate the state of each entity in the context
        // before SaveChanges can succeed.
        foreach (ObjectStateEntry entry in
            ((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
        {
            if (!entry.IsRelationship && (entry.Entity is IHasTimeStamp))
            {
                (entry.Entity as IHasTimeStamp).DoTimeStamp();
            }
        }
    }
}

【讨论】:

  • 干得好!点赞。可能是我的答案和要走的路。
  • 这正是我所需要的,但对 MyEntities 应该在哪里感到困惑?那是 DbContext 类吗?我希望我可以在我的 Web 项目中连接这个事件以保持逻辑,而不是我的 EF 层。谢谢!
  • EF7/Core 中似乎还不支持。
  • @JeremyHolovacs 你可以这样做pastiebin.com/590267121c6db
猜你喜欢
  • 2021-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-28
相关资源
最近更新 更多