in Entity framework, how to call a method on Entity before saving

前端 未结 1 1086
时光取名叫无心
时光取名叫无心 2020-12-24 09:34

Below I have created a demo entity to demonstrate what I\'m looking for:

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

             


        
相关标签:
1条回答
  • 2020-12-24 10:15

    I have an almost identical situation and I manage it by handling the SavingChanges event on the context.

    First I create an interface that defines the timestamping operations:

    public interface IHasTimeStamp
    {
        void DoTimeStamp();
    }
    

    Then I implement this interface in my entities:

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

    The final step is to register the SavingChanges handler and implement it.

    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();
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题