使用 LINQ GroupBy() 从数据库中获取强类型的唯一项列表
Get a strongly typed list of unique items using LINQ GroupBy() from database
如何最好使用 LINQ 与 GroupBy()
一起获得独特项目的列表?
这将是我的尝试:
public IEnumerable<Owner> GetAll(int userId)
{
return _dbContext.Owners.Where(x => x.UserId == userId)
.GroupBy(p => p.Text).Select(x => new Owner()).ToList();
}
但这让我遇到了这个 运行 时间错误:
The entity or complex type 'CentraVent.Data.Owner' cannot be constructed in a LINQ to Entities query.
我不得不说这是我的许多尝试之一。我只能找到 return 匿名类型的例子。如何为强类型对象完成此操作?
EDIT 具有唯一的所有者列表,我的意思是基于 Text
列。因此,Text
列的记录不应具有相同的值。我得到哪个副本并不重要。
所有者 table 具有以下字段:
- 编号
- 文字
- 颜色
- 用户名
如果对于每个唯一 Text
值,您想要哪个 Owner
无关紧要,那么您可以只获得第一个
public IEnumerable<Owner> GetAll(int userId)
{
return _dbContext.Owners.Where(x => x.UserId == userId)
.GroupBy(p => p.Text).Select(x => x.FirstOrDefault()).ToList();
}
也许你是这个意思?
.GroupBy(p => p.Text).Select(x => new { owner = x }).ToList();
或
.GroupBy(p => p.Text).Select(x => new { owner = x.Owner }).ToList();
不看数据模型很难判断
如何最好使用 LINQ 与 GroupBy()
一起获得独特项目的列表?
这将是我的尝试:
public IEnumerable<Owner> GetAll(int userId)
{
return _dbContext.Owners.Where(x => x.UserId == userId)
.GroupBy(p => p.Text).Select(x => new Owner()).ToList();
}
但这让我遇到了这个 运行 时间错误:
The entity or complex type 'CentraVent.Data.Owner' cannot be constructed in a LINQ to Entities query.
我不得不说这是我的许多尝试之一。我只能找到 return 匿名类型的例子。如何为强类型对象完成此操作?
EDIT 具有唯一的所有者列表,我的意思是基于 Text
列。因此,Text
列的记录不应具有相同的值。我得到哪个副本并不重要。
所有者 table 具有以下字段:
- 编号
- 文字
- 颜色
- 用户名
如果对于每个唯一 Text
值,您想要哪个 Owner
无关紧要,那么您可以只获得第一个
public IEnumerable<Owner> GetAll(int userId)
{
return _dbContext.Owners.Where(x => x.UserId == userId)
.GroupBy(p => p.Text).Select(x => x.FirstOrDefault()).ToList();
}
也许你是这个意思?
.GroupBy(p => p.Text).Select(x => new { owner = x }).ToList();
或
.GroupBy(p => p.Text).Select(x => new { owner = x.Owner }).ToList();
不看数据模型很难判断