我想 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/