[英]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. 现在我已经有了它,但是我需要从局部外部调用
db.SaveChanges()
。 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
): 然后在你的上下文的构造函数中(假设它是一个
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;
) (需要
using System.Data.Entity.Core.Objects;
)
The caveats are many: 警告很多:
ChangeStatus
method. ChangeStatus
方法。 ChangeStatus
succeeded. ChangeStatus
是否成功。 Or throw an exception when it didn't? IMyEntityStatusChange
is still alive. IMyEntityStatusChange
仍处于活动状态, IMyEntityStatusChange
已处置的上下文进行垃圾回收。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.