调用SavingChanges时无法解决符号错误

时间:2014-05-20 14:21:24

标签: c# entity-framework dbcontext objectcontext

所有

我正在使用以下MSDN Article但我得到了:"无法解析符号SavingChanges"

有问题的电话是:

contextProxy.SavingChanges += new EventHandler(context_SavingChanges);

contextProxy的类型为: public class ReportingContext:DbContext ,它是我处理所有EF数据模型的上下文类等。因此,如果问题是DBContext不从SavingChanges需要继承(ObjectContext) ?)我该如何解决?

我的实施

public class ReportingProxy
{

    // Define the object context to be provided. 
    private ReportingContext contextProxy = new ReportingContext();

    public ReportingProxy()
    {
        // When the object is initialized, register the  
        // handler for the SavingChanges event.
        contextProxy.SavingChanges += new EventHandler(context_SavingChanges);
    }

    // Method that provides an object context. 
    public ReportingContext Context
    {
        get
        {
            return contextProxy;
        }
    }

    // SavingChanges event handler. 
    private void context_SavingChanges(object sender, EventArgs e)
    {
        var newClubIdToUpdate = 0;

        // Ensure that we are passed an ObjectContext
        ObjectContext context = sender as ObjectContext;
        if (context != null)
        {

            // Validate the state of each entity in the context before SaveChanges can succeed. 
            foreach (ObjectStateEntry entry in
                context.ObjectStateManager.GetObjectStateEntries(
                    EntityState.Added | EntityState.Modified | EntityState.Deleted))
            {

                if (SecurityHelper.IsValidNewClubTableName(entry.EntitySet.Name)) 
                {
                    if (!entry.IsRelationship && (entry.Entity.GetType() == typeof (NewClub)))
                    {
                        var nc = entry.Entity as NewClub;
                        newClubIdToUpdate = (nc != null ? nc.Id : 0);
                    }

                    if (!entry.IsRelationship && (entry.Entity.GetType() == typeof (NewClubProspect)))
                    {
                        var ncp = entry.Entity as NewClubProspect;
                        newClubIdToUpdate = (ncp != null ? ncp.NewClubId : 0);
                    }
                }
            }

            //Update the NewClub.LastActivityDate column
            if (newClubIdToUpdate > 0)
            {
                string q = @"UPDATE NewClub SET LastActivityDate='" + DateTime.Now + "' WHERE Id=" + newClubIdToUpdate;


                using (var cxt = new ReportingContext())
                {
                    var result = cxt.Database.ExecuteSqlCommand(q);
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

SavingChanges上没有DbContext个活动。它仅在ObjectContext上,这是您链接到的MSDN文章的内容。

Here's an article关于如何从DbContext获取它。

为避免链接损坏,以下是针对您的方案修改的示例:

using (var contextProxy = new ReportingContext())
{
    var objCtx = ((IObjectContextAdapter)contextProxy ).ObjectContext;

    objCtx.SavingChanges += new EventHandler(context_SavingChanges);
}