简体   繁体   English

实体框架SaveChanges在EntityObject的扩展部分内

[英]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: 警告很多:

  • The context can be disposed any time, breaking your ChangeStatus method. 可以随时处理上下文,从而破坏ChangeStatus方法。
  • This means that you need some check whether or not ChangeStatus succeeded. 这意味着您需要检查ChangeStatus是否成功。 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. 只要其中一个IMyEntityStatusChange仍处于活动状态, IMyEntityStatusChange已处置的上下文进行垃圾回收。
  • If other properties are changed, these will be persisted as well, maybe before you actually want it. 如果其他属性发生了变化,这些属性也会被保留,也许在您真正想要它之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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