简体   繁体   中英

Entity Framework SaveChanges within extended partial of an EntityObject

I'm extending the partial that was autogenerated to change the status flag of a row on the database. Right now I've got it working, but I need to call db.SaveChanges() from outside of the partial. Is there a way that I can get the current Entities context from within the partial in order to have it save the change immediately?

public partial interface IMyEntityStatusChange
{
    void ChangeStatus(MyEntityStatusCode code);
}

public partial class MyEntity : IMyEntityStatusChange
{
    public void ChangeStatus(MyEntityStatusCode code)
    {
        StatusCode = (int)code;
        //Now I want to Save it to the db
    }
} 

Right now I have To do something like this:

using(var db = new EFEntities())
{
    db.MyEntities.FirstorDefault().ChangeStatus(MyEntityStatusCode.Failed);
    db.SaveChanges();
}

Thank you!

It would break the persistence-ignorant paradigm of Entity Framework, but that aside, there may be a possibility to do this if you insist.

First, you'd need to extend your interface:

internal interface IMyEntityStatusChange
{
    DbContext Context { get; set; }
    void ChangeStatus(MyEntityStatusCode code);
}

Then in the constructor of your context (assuming it's a DbContext ):

((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += 
                                            Context_ObjectMaterialized;

And the method:

void Context_ObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
{
    var contextAwareEntity = e.Entity as IMyEntityStatusChange;
    if (contextAwareEntity != null)
    {
        contextAwareEntity.Context = this;
    }
}

(requires using System.Data.Entity.Core.Objects; )

The caveats are many:

  • The context can be disposed any time, breaking your ChangeStatus method.
  • This means that you need some check whether or not ChangeStatus succeeded. Or throw an exception when it didn't? Not nice either way.
  • A disposed context will not be garbage collected as long as one of these IMyEntityStatusChange is still alive.
  • If other properties are changed, these will be persisted as well, maybe before you actually want it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM