c# - 类x.Savechanges(): No suitable method found to override

标签 c# asp.net entity-framework error-handling

我想 checkout db.SaveChanges()进行错误处理,并将其放入EFentities类的SaveChanges()方法中,但是我对SaveChanges()遇到此错误:

No suitable method found to override



这是我的代码:
public partial class EFentities
{
    EF db = new EF();

    public override int  SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException ex)
        {
            // Retrieve the error messages as a list of strings.
            var errorMessages = ex.EntityValidationErrors
                    .SelectMany(x => x.ValidationErrors)
                    .Select(x => x.ErrorMessage);

            // Join the list to a single string.
            var fullErrorMessage = string.Join("; ", errorMessages);

            // Combine the original exception message with the new one.
            var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

            // Throw a new DbEntityValidationException with the improved exception message.
            throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
        }
    }
}

最佳答案

您没有找到合适的方法来覆盖错误,因为您既没有在部分类的另一侧定义SaveChanges()虚拟方法,也没有定义该虚拟方法继承的任何基类。

带有SaveChanges()签名的 System.Data.Entity.DbContext 类中可用的virtual方法如下:

public virtual int SaveChanges()

因此,您应该添加DbContext作为EFEntities继承的基类,以使override关键字起作用:
using System.Data.Entity;

public partial class EFEntities : DbContext // add this base class
{
    public override int SaveChanges()
    {
        // manual override goes here

        return base.SaveChanges();
    }
}

关于c# - 类x.Savechanges(): No suitable method found to override,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52031442/

相关文章:

c# - 使用自定义数据源时如何隐藏DataGridView的列?

c# - 使类中所有成员的访问修饰符成为一个

jquery - Controller 中的参数在 asp.net mvc 中给出空值异常

asp.net-mvc - 使用 WebApi 进行客户端验证

c# - 注册为 "scoped"或 "transient"的 Dbcontext 是否影响关闭数据库连接

c# - Entity Framework 中数据库条目的版本历史

c# - 触发器在 Sql Server 的 BulkCopy 中不起作用

c# - 从代码后面输出Javascript时如何处理换行符

asp.net - 如何从 SQL 表中的列获取 XML 数据?

javascript - 使用 CheckBox 启用 CheckBoxList? - ASP.NET