【发布时间】:2019-05-23 18:49:09
【问题描述】:
var result = Context.ItemSet
.OrderBy(o => o.Index)
/*.Include(t => t.Group) with this, item with id 500 is outputted 4 times, without it is outputted 2 times*/
.ToList();
for (int i = 0; i < result.Count(); i++)
{
Debug.WriteLine("-"+i);
Debug.WriteLine(result[i].Id);
}
以上代码输出如下:
> -0
> 1
> -1
> 11
> -2
> 12
> -3
...
> -30
> 17
> -31
> 206
> -32
> 500 //
> -33
> 500 //duplicate
> -34
> 203
为什么结果列表多次包含相同的数据,我该如何防止这种情况发生?我不能不使用select distinct id,因为我需要所有列。
【问题讨论】:
-
Id字段真的是唯一的吗?如果直接对数据库运行查询(不涉及 C#)会发生什么? -
是的,它是独一无二的,因为在数据库中运行查询时,它只返回 id 为 500 的一行
-
如果你进入数据库并选择 * from itemset where id=500 你会得到多少条记录?
-
只有一个@RuiLima
-
当查询返回多个对象(文档here)时,调用
Single()会抛出InvalidOperationException,这是一个强有力的指标,表明您的数据源包含多个带有Id = 500的条目。如果在数据库中运行查询返回一条记录,如你之前所说的id=500,那么我只能建议你尝试验证调用ToList()时生成的SQL并手动检查它是否正确。
标签: c# sql duplicates