EF Core SaveChanges是否針對數據註釋進行驗證

c# data-annotations entity-framework-core

我有一個帶有數據註釋的模型,我想知道如果數據註釋失敗,是否有可能使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 Controller方法:

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%" ]
  }
}

一般承認的答案

根據與此問題相關的github問題 ,Entity Framework Core不會執行自動數據驗證。

還有的是沒有核心出現在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();
        }
    }

這將驗證您的數據註釋,並在驗證失敗時拋出異常。



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow