ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# – Entity Framework / Linq – 获取动态指定属性的不同值

2019-07-03 16:55:38  阅读:193  来源: 互联网

标签: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)

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

另一个问题中的某个人使用ParameterExpression和Expression类得到了类似的答案,但实际上没有提供足够的信息来帮助我完成我的具体任务.

我也尝试过反射,但当然Linq在Select表达式中并不那么喜欢.

我会使用if并称之为好,但实际的表/对象中确实存在大量的字段/属性,因此它不切实际.如果基表发生变化,这也可以节省一些重构.

我正在尝试做的SQL版本:

SELECT Distinct [usersuppliedfieldname] from TableName where [someotherconditionsexist]

我已经拥有的伪代码:

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)

    }
}

解决方法:

您可以尝试这样的事情(类似于建议重复的帖子)

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

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

var values = context.Tests.Select<Test, int>("Property2").Distinct();

标签:c,linq,entity-framework-5
来源: https://codeday.me/bug/20190703/1368386.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有