【问题标题】:Does EF Core SaveChanges validate against the data annotationsEF Core SaveChanges 是否针对数据注释进行验证
【发布时间】:2017-03-01 21:06:22
【问题描述】:

我有一个带有数据注释的模型,我想知道如果数据注释失败,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();
    }

这是我的 project.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 不像 EF6 那样执行数据验证。
  • @stephen.vakil 您应该将其发布为答案,而不是评论。 ;-)

标签: c# data-annotations entity-framework-core


【解决方案1】:

根据a github issue related to this question,Entity Framework Core 不执行自动数据验证。

在 EF6 中提供了一些更新的功能列表,这些功能不在 Core here 中。

【讨论】:

    【解决方案2】:

    您可以通过覆盖 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();
            }
        }
    

    这将根据您的数据注释进行验证,并在验证失败时抛出异常。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2010-12-06
    • 1970-01-01
    相关资源
    最近更新 更多