按名称获取类属性

时间:2016-01-13 19:49:32

标签: c# entity-framework casting

我重写了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)>)

但当然这是一个变量,不能作为通用类型传递

1 个答案:

答案 0 :(得分:0)

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

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

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));

希望它有所帮助。