我有一个基本的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>只是在所有模型上加上属性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核心未引发ValidationException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54058196/

10-09 09:13