EF Core SaveChanges是否对数据注释进行验证?

本文关键字:验证 注释 数据 Core SaveChanges 是否 EF | 更新日期: 2023-09-27 18:06:55

我有一个数据注释的模型,我想知道如果数据注释失败,是否有可能使SaveChanges方法失败?

我期待SaveChanges抛出一个异常,"Test2超出了2到4的范围"。相反,它将保存到数据库中。

例如,下面是我的测试实体:

public class Visit
{
    public int Id { get; set; }
    [MaxLength(2)]
    public string Test { get; set; }
    [Range(2, 4)]
    public int Test2 { get; set; }
}

这里是上下文:

public class Context : DbContext
{
    public Context()
    {
    }
    public Context(DbContextOptions<Context> options)
            : base(options)
    {
    }
    public DbSet<Visit> Visits { get; set; }
}

这是我用来测试它的非常简单的MVC控制器方法:

public HomeController(Context context)
    {
        context.Visits.Add(new Visit() {Test = "21", Test2 = 3423});
        var results = context.SaveChanges();
    }

这是我的项目。json文件:

{
  "dependencies": {
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0",
    "System.ComponentModel.Annotations": "4.1.0"
  },
  "tools": {
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
      },
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },
  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },
  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "Areas/**/Views",
      "appsettings.json",
      "web.config"
    ]
  },
  "scripts": {
    "prepublish": [ "bower install", "dotnet bundle" ],
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

EF Core SaveChanges是否对数据注释进行验证?

根据与此问题相关的github问题,实体框架核心不执行自动数据验证。

这里有一个EF6中没有的功能更新列表

您可以通过重写SaveChanges来实现您自己的验证:

class Context : DbContext
    {
        public override int SaveChanges()
        {
            var entities = from e in ChangeTracker.Entries()
                           where e.State == EntityState.Added
                               || e.State == EntityState.Modified
                           select e.Entity;
            foreach (var entity in entities)
            {
                var validationContext = new ValidationContext(entity);
                Validator.ValidateObject(entity, validationContext);
            }
            return base.SaveChanges();
        }
    }

这将根据您的数据注释进行验证,如果验证失败则抛出异常。