我有一个带有数据注释的模型,我想知道如果数据注释失败,是否有可能让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%" ]
}
}
答案 0 :(得分:2)
根据a github issue related to this question,Entity Framework Core不会执行自动数据验证。
EF6中存在的某些更新功能列表在核心here中没有。
答案 1 :(得分:1)
您可以通过覆盖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();
}
}
这将验证您的数据注释,并在验证失败时抛出异常。