gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:31:55 29 4
gpt4 key购买 nike

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

因此,假设表 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);
}
}

对于我的测试,我创建了一组名为 Tests 的虚拟实体,下面是从 Property2

获取不同值的查询
var values = context.Tests.Select<Test, int>("Property2").Distinct();

关于c# - Entity Framework /Linq - 获取动态指定属性的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18318778/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com