实体框架/ Linq-获取动态指定属性的不同值

Mat*_*att 5 c# linq entity-framework-5

我需要获取一组实体的特定属性的不同值的列表。

因此,假设表A具有字段x,y,z,1、2、3,其中x是PK(因此不在表中)。

我需要获取y,z,1、2或3的所有唯一值,而不必在我的方法中知道我要获取哪个字段。因此,该方法的模式为:

public List<ObjectName> GetUniqueFieldValues(string fieldname)
Run Code Online (Sandbox Code Playgroud)

“ ObjectName”对象是具有两个属性的对象,以上方法将为每个结果填充至少一个属性。

另一个问题中的某个人使用ParameterExpression和Expression类也有类似的答案,但实际上并没有提供足够的信息来帮助我完成特定任务。

我也尝试过反射,但是Linq在Select表达式中当然不太喜欢它。

我只会使用if并将其命名为好,但是实际表/对象中确实有大量字段/属性,因此这是不切实际的。如果基表发生变化,这也将为我节省一些重构。

我要执行的SQL版本:

SELECT Distinct [usersuppliedfieldname] from TableName where [someotherconditionsexist]
Run Code Online (Sandbox Code Playgroud)

我已经拥有的伪代码:

public List<ReturnObject> GetUniqueFieldValues(int FkId, ConditionObject searchmeta)
{
    using(DbEntities db = new DbEntities())
    {
        // just getting the basic set of results, notice this is "Select *"
        var results = from f in db.Table
                      where f.FkId == FkId && [some static conditions]
                      select f;

        // filtering the initial results by some criteria in the "searchmeta" object
        results = ApplyMoreConditions(results, searchmeta);

        //  GOAL - Select and return only distinct field(s) specified in searchmeta.FieldName)

    }
}
Run Code Online (Sandbox Code Playgroud)

mlo*_*ske 3

您可以尝试类似的操作(类似于建议重复的帖子)

public static class DynamicQuerier
{
    private delegate IQueryable<TResult> QueryableMonad<TInput, TResult>(IQueryable<TInput> input, Expression<Func<TInput, TResult>> mapper);

    public static IQueryable<TResult> Select<TInput, TResult>(this IQueryable<TInput> input, string propertyName)
    {
        var property = typeof (TInput).GetProperty(propertyName);
        return CreateSelector<TInput, TResult>(input, property, Queryable.Select);
    }

    private static IQueryable<TResult> CreateSelector<TInput, TResult>(IQueryable<TInput> input, MemberInfo property, QueryableMonad<TInput, TResult> method)
    {
        var source = Expression.Parameter(typeof(TInput), "x");
        Expression propertyAccessor = Expression.MakeMemberAccess(source, property);
        var expression = Expression.Lambda<Func<TInput, TResult>>(propertyAccessor, source);
        return method(input, expression);
    }
}
Run Code Online (Sandbox Code Playgroud)

对于我的测试,我创建了一组名为 的虚拟实体Tests,下面是从 中获取不同值的查询Property2

var values = context.Tests.Select<Test, int>("Property2").Distinct();
Run Code Online (Sandbox Code Playgroud)