c# - 我在 EntityFramework 5 中找不到 System.Data.Entity.Validation

标签 c# entity-framework asp.net-mvc-5

尝试使用以下代码将对象保存到数据库时遇到DbEntityValidationException:

public void Save(Employee emp)
{
    repository.Insert(emp);
    unitOfWork.SaveChanges();               
}

然后我尝试使用以下内容抛出异常的详细信息:

try
{
    repository.Insert(emp);
    unitOfWork.SaveChanges();
}
catch (DbEntityValidationException ex)
{             
    var errorMessages = ex.EntityValidationErrors
        .SelectMany(x => x.ValidationErrors)
        .Select(x => x.ErrorMessage);
    var fullErrorMessage = string.Join("; ", errorMessages);
    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);
}

现在我收到以下错误,并且我似乎无法在任何地方看到 System.Data.Entity.Validation 添加到我的引用中以清除此错误消息:

The type or namespace name 'DbEntityValidationException' could not be found (are you missing a using directive or an assembly reference?)

我该如何解决这个问题?

更新 我刚刚注意到我的 EF 的运行时版本是 4.030319。这可能是原因吗? enter image description here

最佳答案

在 Entity Framework 5 中,DbEntityValidationException 类在 System.Data.Entity.Validation 命名空间(位于 EntityFramework dll 中)中定义。您需要为此命名空间包含一个 using 语句,以便属于该命名空间的类在您的类中可用。

将此行添加到您的类中,然后您应该能够使用此异常类。

using System.Data.Entity.Validation;

关于c# - 我在 EntityFramework 5 中找不到 System.Data.Entity.Validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34456001/

相关文章:

c# - 局部敏感哈希实现?

c# - SQL 表上的 XML 读取器返回无效 XML

entity-framework - 如何将 Entity Framework 包含扩展方法引入通用 IQueryable<TSource>

c# - Entity Framework code first - 不是为了创建表吗?

asp.net-mvc-5 - RavenDb 的 KeyNotFoundException

c# - 如何在 Portal C# 应用程序功能中访问 Azure 功能中的应用程序设置?

c# - 如何以编程方式单击节点?

c# - 使用 Entity Framework 包含查询运行速度极慢

asp.net-mvc-5 - ASP.NET MVC 5 自定义 RazorViewEngine 用于多个门户结构

c# - ASP.Net MVC 5 图片上传到文件夹