使用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方法的?
更新:
现在,我在上下文类和SaveChanges中覆盖ValidateEntity方法,但是当我编辑实体并在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);
}
}
}
}
由于无法覆盖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;
}
我希望可以覆盖保存更改,但是现在必须这样做。感谢大家的帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句