我收到了一个错误,这让我非常伤心......我在我的项目中添加了一个部分类,并为它的名字添加了SaveChangeExeptionEntities ...
我收到了这个错误:
对象不包含“SaveChanges”的定义
这是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Validation;
using System.ComponentModel;
namespace WindowsFormsApplication6
{
public partial class SaveChangeExeptionEntities
{
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);
}
}
}
}
请帮助我!我要发疯了:(
答案 0 :(得分:0)
你有一个不是从任何东西继承的部分课程。你不能做base.SaveChanges();
,因为你没有基础
这里有部分信息: https://msdn.microsoft.com/en-us/library/wa80x488(v=vs.110).aspx
这里是基本调用(你可以看到继承) https://msdn.microsoft.com/it-it/library/hfw7t1ce.aspx
部分类的一个例子:
public partial class CoOrds
{
private int x;
private int y;
public CoOrds(int x, int y)
{
this.x = x;
this.y = y;
}
}
public partial class CoOrds
{
public void PrintCoOrds()
{
Console.WriteLine("CoOrds: {0},{1}", x, y);
}
}
class TestCoOrds
{
static void Main()
{
CoOrds myCoOrds = new CoOrds(10, 15);
myCoOrds.PrintCoOrds();
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
你可以看到对象myCoOrds是使用在partial的第一部分中编写的costructor实现的,并且使用在partial类的第二部分中编写的方法...希望它有助于理解更好
答案 1 :(得分:0)
base指的是System.Windows.Forms.Form,你继承了它。表格没有任何SaveChanges调用,EF有。您只需要在Try Catch块中结束保存更改调用。
你在这里混淆使用Partial Class。
你也可以这样做
public class ExtendedClass : BaseEFClassForMyEntity
{
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (exception ex)
{
}
}
}
现在创建ExtendedClass
的实例并完成
答案 2 :(得分:0)
看来你正在使用实体框架!!你必须在你的DbContext类中编写这个方法。
public partial class ApplicationDbContext : DbContext
{
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);
}
}
}