按名称获取类属性

本文关键字:属性 获取 | 更新日期: 2023-09-27 18:30:16

我正在重写 ValidateEntity 方法来检查唯一验证,但我遇到了一个绊脚石。

protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
    var result = new DbEntityValidationResult(entityEntry, new List<DbValidationError>());
    if (entityEntry.Entity is ReferenceType && entityEntry.State == EntityState.Added)
    {
        var entity = entityEntry.Entity as ReferenceType;
        var pluralService = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en-gb"));
        var pluralEntity = pluralService.Pluralize(entity.GetType().Name);
        // I would like Courses to be replaced with the property name of pluralEntity
        if (Courses.Where(x => x.Title == entity.Title).Count() > 0)
        {
            result.ValidationErrors.Add(new DbValidationError(nameof(entity.Title), nameof(entity.Title) + " must be unique."));
        }
    }
    if (result.ValidationErrors.Count > 0)
    {
        return result;
    }
    else
    {
        return base.ValidateEntity(entityEntry, items);
    }
}

在我的SchoolContext类中,我有一个属性DbSet<Course> Courses,它是一个ReferenceType(一种自定义抽象类类型)。

pluralEntity的值是课程,但我想在 if 语句中加入类似于以下内容的内容:

if (Property(pluralEntity).Where(x => x.Title == entity.Title).Count() > 0)
{
    // validate
}

有没有办法做到这一点?

更新我有这个:

var prop = (DbSet<ReferenceType>) GetType().GetProperty(pluralEntity).GetValue(this, null);
if (prop.Where(x => x.Title == entity.Title).Count() > 0)
{
    result.ValidationErrors.Add(new DbValidationError(nameof(entity.Title), nameof(entity.Title) + " must be unique."));
}

但是ReferenceType是一个抽象类,所以它不能在运行时强制转换它。

我想做这样的事情

var prop = (DbSet<typeof(entityEntry.Entity.GetType().Name)>)

但当然,这是一个变量,不能作为泛型类型传入

按名称获取类属性

目前我唯一能想到的就是使用存储库模式编写自定义验证方法。

首先,创建一个所有实体都将实现的接口

public interface IEntity
{
    public string Title {get; set; }
}

然后创建存储库:

public class Repository<TEntity> where TEntity: class, IEntity
{
    private YourContext context = new YourContext();
    private DbSet<TEntity> AppDbSet;
    public Repository()
    {
        AppDbSet = context.Set<TEntity>();
    }
    //a couple of method to retrieve data...
    public List<TEntity> GetAll()
    {
        return AppDbSet.ToList();
    }
    public IEnumerable<TEntity> Find(Func<TEntity, bool> predicate)
    {
        return AppDbSet.Where<TEntity>(predicate);
    }
    public TEntity Single(Func<TEntity, bool> predicate)
    {
        return AppDbSet.FirstOrDefault(predicate);
    }
    //Lastly, implement a validation method
    public bool IsValid(TEntity entity)
    {
        if (AppDbSet.SingleOrDefault(x => x.Title == entity.Title) != null)
            return false;
        else
            return true;
    }
}

按如下方式使用存储库:

Repository<Course> courseRepository = new Repository<Course>();
Course course = new Course();
course.Title = "Boring course";
Console.WriteLine(courseRepository.IsValid(course));

希望对您有所帮助。