【发布时间】:2021-02-01 13:01:43
【问题描述】:
我正在尝试针对实体框架DbSet 运行 Distinct 查询。这些列表用于填充 UI 中的 Select,以过滤 TRecord 的数据集。下面列出了完整的方法。 fieldName 是 DbSet 中的字段之一。下面的代码有效,但效率低下。如果您尝试直接在DbSet 上使用Distinct(),它不会做不同的事情 - 只是返回完整的数据集。我假设问题在于我使用反射来获取价值的方式。有解决办法吗?
public async static Task<List<string>> GetDistinctListAsync<TRecord>(this DbContext context, string fieldName) where TRecord : class, IDbRecord<TRecord>, new()
{
// Get the DbSet for TRecord
var dbset = GetDbSet<TRecord>(context, null);
// declare list as an empty list
var list = new List<string>();
// Get the filter propertyinfo object
var x = typeof(TRecord).GetProperty(fieldName);
if (dbset != null && x != null)
{
// we get the full list and then run a distinct because we can't run a distinct directly on the dbSet
var fulllist = await dbset.Select(item => x.GetValue(item).ToString()).ToListAsync();
list = fulllist.Distinct().ToList();
}
return list ?? new List<string>();
}
我正在修改使用通过DbSet.FromSQLRaw() 调用的 SQL Distinct Query 的旧代码。
【问题讨论】:
-
您能否包含您要翻译的代码?
-
效率低下,因为您获取所有内容并在内存中处理它......这个帖子可能会有所帮助:stackoverflow.com/questions/32619338/…
-
嗨,Alexandru,下面的问题回答了我的问题,所以我不会再麻烦你了。我的生产代码在 DbSet.FromSQLRaw() 上运行,我试图摆脱原始 SQL。
标签: c# entity-framework distinct