【问题标题】:Class x.Savechanges(): No suitable method found to override类 x.Savechanges():找不到合适的方法来覆盖
【发布时间】:2019-02-01 12:39:22
【问题描述】:

我想检查db.SaveChanges() 的错误处理,我把它放到EFentities 类的SaveChanges() 方法中,但是我对SaveChanges() 有这个错误:

找不到合适的方法来覆盖

这是我的代码:

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

【问题讨论】:

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


    【解决方案1】:

    您收到 No suitable methode found to override 错误,因为您既没有在部分类的另一端定义 SaveChanges() 虚拟方法,也没有定义虚拟方法继承的任何基类来自。

    System.Data.Entity.DbContext 类中的SaveChanges() 方法可用,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();
        }
    }
    

    【讨论】:

    • public virtual int SaveChanges() 有什么用?
    • 这是DbContext 类中声明的方法名(参见参考资料)。您需要覆盖该方法才能使用您自己的自定义SaveChanges()
    • 我运行了代码并没有 savechanges() 保存数据并显示错误我的意思是没有去 cach()
    • 目前您似乎遇到了不同的问题,而不是上面出现的错误。您可以为此创建另一个问题并提供必要的详细信息以供进一步分析。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多