gpt4 book ai didi

c# - EF Core 没有引发 ValidationException

转载 作者:行者123 更新时间:2023-11-30 21:30:40 26 4
gpt4 key购买 nike

我有一个基地DbContext喜欢上课

public abstract class DbContextBase : DbContext
{
public DbContextBase()
{
}

public DbContextBase(DbContextOptions options)
: base(options)
{
}

public override int SaveChanges()
{
this.ValidateEntities();

return base.SaveChanges();
}

public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
this.ValidateEntities();

return base.SaveChangesAsync(cancellationToken);
}

public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
{
this.ValidateEntities();

return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}

protected virtual void ValidateEntities()
{
var entities = this.ChangeTracker.Entries().
Where(s => s.State == EntityState.Added || s.State == EntityState.Modified);

foreach (var entity in entities)
{
var validationContext = new ValidationContext(entity);
Validator.ValidateObject(entity, validationContext);
}
}
}

我所有的 Db Context 类都继承自这个基类。问题是 Validator.ValidateObject() 行不扔ValidationException即使存在验证违规。在调试器中,我可以看到该行已执行。例如,对于下面的模型类,我尝试调用 SaveChangesAsync()Name设置为 null但是验证通过了:

public class MyModel : IEntity<long>
{
[Key]
public long Id { get; set; }

[Required]
public string Name { get; set; }
}

IEntity<T>只是强加属性(property)Id在所有型号上。

最佳答案

问题是变量 entity 不包含实体实例,而是更改跟踪器 (EntityEntry) 实例,因此代码试图验证错误的东西。

因此要么重命名变量并使用 entry.Entity 属性:

var entries = this.ChangeTracker.Entries()
.Where(s => s.State == EntityState.Added || s.State == EntityState.Modified);

foreach (var entry in entries)
{
var validationContext = new ValidationContext(entry.Entity);
Validator.ValidateObject(entry.Entity, validationContext);
}

或保持代码不变,但要确保 entities 变量包含可枚举的实体实例:

var entities = this.ChangeTracker.Entries()
.Where(s => s.State == EntityState.Added || s.State == EntityState.Modified)
.Select(s => s.Entity); // <--

关于c# - EF Core 没有引发 ValidationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54058196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com