c# - 在 Entity Framework 中,如何在保存之前调用实体上的方法

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

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

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 接口(interface)来使这个实体 self 验证。

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

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

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

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

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

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

最佳答案

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

首先,我创建了一个定义时间戳操作的接口(interface):

public interface IHasTimeStamp
{
    void DoTimeStamp();
}

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

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

关于c# - 在 Entity Framework 中,如何在保存之前调用实体上的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6677160/

相关文章:

entity-framework - 身份规范设置为false

entity-framework-4 - 首先在 Entity Framework 代码中使用导航属性

c# - 无法加载文件或程序集“Microsoft.Extensions.Logging,版本=7.0.0.0,文化=中性,系统找不到指定的文件”

c# - MB 和字节之间的文件大小差异

c# - 如何修复异常无法加载文件或程序集 'EntityFramework, Version=4.0.0.0[...]' 或其依赖项之一

c# - 提取由 DbContext.OnModelCreating 在 IDatabaseInitializer 中创建的配置

c# - 维护网站的在线 (Azure) 和离线版本

c# - 基于流获取数据

c# - .NET Core 2.1 中的 HttpContext.GetTokenAsync 无法检索 JWT

c# - 使用与表相同类型的 View