覆盖Entity Framework 5中的SaveChanges

时间:2014-12-01 21:29:23

标签: entity-framework entity-framework-5 asp.net-dynamic-data

使用C#,我使用"从数据库生成"生成了我的数据库模型。使用T4模板生成POCO类和上下文。一切都工作正常,应用程序能够编辑,插入等,除了我不能覆盖我的实体类中的SaveChanges方法。我需要这样做来添加商业逻辑。这是上下文类:

//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace WebApplication1
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

   public partial class IInvoiceEntities2 : DbContext
   {
        public IInvoiceEntities2 ()
            : base("name=IInvoiceEntities2 ")
        {
        }        


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }






    public DbSet<Company> Companies { get; set; }
    public DbSet<CompanyDetail> CompanyDetails { get; set; }
    public DbSet<CompanyVersion> CompanyVersions { get; set; }
    public DbSet<CustomerDetail> CustomerDetails { get; set; }
    }
}

当我在其中设置断点并编辑实体时,我的SaveChanges方法没有被击中的任何想法?

更新

我现在覆盖上下文类中的ValidateEntity方法以及SaveChanges,但是当我编辑实体并在SaveChanges或ValidateEntity中设置断点时,两种方法都没有被调用(参见上面的代码)

更新2:

我现在在App_Code文件夹中为SaveChanges和ValidateEntity创建了一个部分类,但这些方法仍未执行:

namespace WebApplication1
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

public partial class IInvoiceEntities2 : DbContext
{
    public IInvoiceEntities2 ()
        : base("name=IInvoiceEntities2 ")
    {
    }


    public override int SaveChanges()
    {
        return base.SaveChanges();
    }




protected override DbEntityValidationResult ValidateEntity(
System.Data.Entity.Infrastructure.DbEntityEntry entityEntry,
IDictionary<object, object> items)
{
  // do stuff

    if (result.ValidationErrors.Count > 0)
    {
        return result;
    }
    else
    {
        return base.ValidateEntity(entityEntry, items);
    }
}





}

}

3 个答案:

答案 0 :(得分:4)

如果要覆盖保存更改,可以使用此部分类样式,应注意如果此处的方法未被调用,则通常指示部分类与实际类不匹配,检查命名空间等。

public partial class MyEntities : DbContext
{
    public override int SaveChanges()
    {
        try
        {
            SavingChanges();
            return base.SaveChanges();
        }
        catch (Exception exception)
        {
            //handle errors here
        }
    }

    private void SavingChanges()
    {
        using (var OC = new MyEntities())
        {
            var objects = this.ChangeTracker.Entries()
                .Where(p => p.State == EntityState.Added || 
                    p.State == EntityState.Deleted || 
                    p.State == EntityState.Modified);

            // handle auditing
            AuditingHelperUtility.ProcessAuditFields(
                objects.Where(p => p.State == EntityState.Added));
            AuditingHelperUtility.ProcessAuditFields(
                objects.Where(p => p.State == EntityState.Modified), InsertMode: false);

            // Inserted objects
            foreach (DbEntityEntry entry in objects
                .Where(p => p.State == EntityState.Added))
            {
                if (entry.Entity != null)
                {
                    // insert code 
                }
            }

            // Updated objects
            foreach (DbEntityEntry entry in objects
                .Where(p => p.State == EntityState.Modified))
            {
                if (entry.Entity != null)
                {
                    // update code 
                }
            }

            // Delete objects
            foreach (DbEntityEntry entry in objects
                .Where(p => p.State == EntityState.Deleted))
            {
                if (entry.Entity != null)
                {
                    // delete code 
                }
            }
        }
    }
}

答案 1 :(得分:1)

我已经为这个问题提出了一个可靠的解决方法,因为我无法覆盖SaveChanges()。相反,我实现了EntityDataSource的OnUpdating事件:

<asp:EntityDataSource ID="DetailsDataSource" runat="server" EnableUpdate="true"     
OnUpdating="DetailsDataSource_Updating" />

然后我在我的代码后面有这个方法,允许我进行服务器端验证:

protected void DetailsDataSource_Updating(object sender, EntityDataSourceChangingEventArgs e)
    {
        Country c = (Country) e.Entity;
        if (c.CountryName != "North pole")
            e.Cancel = true;
    }

我希望我可以覆盖保存更改,但现在必须这样做。谢谢大家的帮助。

答案 2 :(得分:0)

注意我只在EF6中测试了这个而不是EF5

覆盖所有场景(包括EntityDataSource)的方法是在底层ObjectContext的SavingChanges事件中添加一个处理程序。这可以从您的DbContext构造函数完成:

 var objCx = (this as IObjectContextAdapter).ObjectContext;
 objCx.SavingChanges += (s, e) => { .... }