Reputation: 364
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!
Upvotes: 0
Views: 493
Reputation: 109175
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:
ChangeStatus
method.ChangeStatus
succeeded. Or throw an exception when it didn't? Not nice either way.IMyEntityStatusChange
is still alive.Upvotes: 2