首页 \ 问答 \ 覆盖Entity Framework 5中的SaveChanges(Override SaveChanges in Entity Framework 5)

覆盖Entity Framework 5中的SaveChanges(Override SaveChanges in Entity Framework 5)

使用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);
    }
}





}

}


Using C#, I've generated my DB model using "Generate from Database". The POCO classes and context are generated with T4 templates. everything is working fine and the app is able to edit, insert etc. except I cannot override the SaveChanges method in my entities class. I need to do this to add buisiness logic. Here is the context class:

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

Any ideas why my SaveChanges method isn't being hit when I set a breakpoint in it and edit an entity?

Update:

I now override the ValidateEntity method in my context class as well as SaveChanges, but when I edit an entity and set a breakpoint in SaveChanges or ValidateEntity, neither methods are being called (see code above)

Update 2:

I've now created a partial class in App_Code folder for the SaveChanges and ValidateEntity, but these methods are still not being executed :

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





}

}


原文:https://stackoverflow.com/questions/27237672
更新时间:2023-09-29 13:09

相关问答

更多
  • 您可以通过首先确保性能计数器事件使用特定属性值( OpenMappedContext() )或特定类型/名称空间来标记。 var log = LogProvider.For() log.Info(...); 在配置Serilog时,应用过滤器的子记录器可以将所需的事件发送到第二个文件。 Log.Logger = new LoggerConfiguration() .WriteTo.Logger(lc => lc .Fil ...
  • 好的,我发现了问题所在。 从使用JaminSec的原始项目开始,它需要升级,因为它使用的是旧组件。 所以我将Serilog升级到当前的v1.5x,并包含当前版本的Serilog.Sinks.Logentries v1.5.8。 由于依赖性问题,COM-Interop将始终失败。 然而Logentries声称它兼容..它在.NET中运行良好,但不是COM! 答案是将Serilog降级到v1.4.x !!! 它作为COM-INTEROP正常工作! Ok so I discovered what the prob ...
  • {d1}将无法识别的类型(如此处的匿名类型{d1}转换为string s以进行日志记录,即使用ToString() 。 因此,第一个示例中的日志事件最终将使用类似的属性(此处为JSON): { "d1": "{ x = 5, y = 88 }" } 使用{@d1}将导致参数序列化为结构化数据: { "d1": { "x": 5, "y": 88 } } 在适当的情况下,第二个例子对于操作/分析更有用。 这种“选择加入”要求的原因是.NET程序中的大多数类型很好地转换为字符 ...
  • 事实证明,我在主装配中引用了一个比我在子装配中更老的nuget包。 更新后,他们匹配问题就消失了。 Turns out I was referencing an older nuget package in my Main Assembly than I was in the sub assembly. After updating them so they match the problem went away.
  • 问题是记录器在您正在测试的设备/仿真器/模拟器的上下文中写入。 所以C:\\log.txt意味着它正试图写入设备上的该目录。 Android - 文件记录 对于Android,您可以使用外部文件目录,因为它不需要运行时权限,可以通过文件浏览器或adb轻松访问。 位置类似于\Android\data\\files 。 protected override IMvxLogProvider CreateLogProvider() { var external ...
  • 试试下面: var log = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.RollingFile(@"f:\log\log.txt", retainedFileCountLimit:7) .CreateLogger(); 日志文件的名称将自动记录-20150819.txt等。您不需要指定日期。 Try below: var log = new LoggerConfigu ...
  • Serilog软件包是其他两个软件包的依赖项,因此通过安装它们,将自动安装核心Serilog软件包。 The Serilog package is a dependency of the other two, so by installing either, the core Serilog package will be installed automatically.
  • 这是Serilog文档 对于此任务,Serilog提供@deconstruction运算符。 var sensorInput = new { Latitude = 25, Longitude = 134 }; Log.Information("Processing {@SensorInput}", sensorInput); 你可以看到要进行解构,你必须在键名之前设置@。 您的示例代码中遗漏了这一点 logger.Debug("Employee details {Employee}", employee) ...
  • 您可以将Serilog的消息格式转换为标准的.NET格式字符串( {0}等),如下所示: var parser = new MessageTemplateParser(); var template = parser.Parse(template); var format = new StringBuilder(); var index = 0; foreach (var tok in template.Tokens) { if (tok is TextToken) format.A ...
  • 这是相当明显的,因为在bin文件夹中该文件不称为appsettings.json,它的名称为TestMvcApp.runtimeconfig.json。 TestMvcApp.runtimeconfig.json不是你的appsettings.json ,它是一个运行时配置文件,因为它从文件名中清楚可见。 我敢打赌,你的appsettings.json在构建过程中不会被复制到输出目录。 要在Visual Studio解决方案资源appsettings.json中修复选择appsettings.json ,请 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)