entity-framework - 覆盖 Entity Framework 5 中的 SaveChanges

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

使用 C#,我使用“从数据库生成”生成了我的数据库模型。 POCO 类和上下文是使用 T4 模板生成的。一切正常,应用程序能够编辑、插入等,除了我无法覆盖我的实体类中的 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);
    }
}





}

最佳答案

如果你想覆盖保存更改,你可以使用这种分部类样式,需要注意的是,如果这里的方法没有被调用,这通常表明分部类与实际类不匹配,检查命名空间等。

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 
                }
            }
        }
    }
}

关于entity-framework - 覆盖 Entity Framework 5 中的 SaveChanges,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27237672/

相关文章:

entity-framework - 使用 edmx 设计器将 Entity Framework 中的列合并为一列

c# - 防止 Entity Framework 5 查询 Information_Schema_Tables

c# - 使用 ASP.NET 动态数据实体过滤表中的行

entity-framework - EF6 在更新时将日期时间设置为 Null

entity-framework - 从 AutoFac 解析 IDbSet<T>

c# - EF 的多个上下文中的多个 SELECT 是否需要 MARS?

c# - 如何构建 IEnumerable<int>.Contains() 表达式?

c# - 如何使用 Entity Framework 4 访问存储过程的 'Results'、 'Messages' 和 'Return Value'?

entity-framework - EF 代码优先 : How to load related data (parent-child-grandchild)?

sql - 如何在内容类型中最好地集成现有数据库数据