元数据属性未在部分类上验证

时间:2017-07-10 14:49:13

标签: c# asp.net entity-framework

我正在尝试将属性添加到由自动生成的类创建的现有参数(Entity Framework Core数据库类,每次从数据库更新时都会覆盖这些类)。 但是,作为元数据添加的属性未经过验证。直接向生成的类添加属性。

生成的部分类:

namespace DataAccess.Data.DatabaseContext.Models
{
    public partial class Customer
    {
        //Validation works if directly applied to the class

        //[Range(1, int.MaxValue)] 
        public int CustomerNo { get; set; }

        // [Required]
        public int? HouseNo { get; set; }

创建了部分类+ MetaData类

namespace DataAccess.Data.DatabaseContext.Models
{
    [MetadataType(typeof(Metadata))]
    public partial class Customer
    {
    }

    public class Metadata
    {
        // These attributes are never validated 

        [Range(1, int.MaxValue)] 
        public int CustomerNo { get; set; }

        [Required]
        public int? HouseNo { get; set; }
    }
}

代码I用于验证每次保存更改时(EF Core):

    public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
        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, true);
        }

        return await base.SaveChangesAsync();
    } 

0 个答案:

没有答案