开发者

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

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

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

I am implementing IValidatableObject interface to make this entity SelfValidating.

Now currently to create new User iam doing this

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

Iam planning to shift u.CreationDate=DateTime.Now; code inside User class. And implement an interface that provides a method which will be executed before saving and after validating

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

now to create a new user I just have to do as below, note that I didn't added date property this time, Class does that automatically.

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

To update user, UpdatedOnDate property will be automatically updated by class

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

My Question: is there any existing interface that provides some method that gets called before Save and AfterValidate or some other ways of doing this, that I may not be knowing.

Or, if I create my custom interface, how can I make its method to get executed in the order I want.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜