gpt4 book ai didi

c# - 迭代 LINQ 实体结果

转载 作者:行者123 更新时间:2023-11-30 14:20:40 25 4
gpt4 key购买 nike

我有一段我认为非常简单的代码,但结果却让我感到困惑。我正在使用 LINQ 查询实体,然后遍历结果以创建一个数组。我正在观察进出数据库的流量,那里的一切看起来都很好。当我复制 LINQ 发送到 SQL 的查询并直接针对 SQL 运行它时,我得到了预期的结果。但是,当我遍历结果时——甚至观察结果时——每条记录都完全相同。这不是 SQL 返回的内容。不是。我做错了什么?

var eventList = from e in entityContext.AuctionSet select e;

ArrayList DayArray = new ArrayList();
int i = 0;

foreach (Auction ae in eventList)
{
// If I put a watch on eventList all the records are the same!
Auction temp = ae; // Even tried copying to a temp value per another solution

// Even though the records are different in the database,
// and the correct number of records are returned, EVERY "ae" instance
// has the exact same values!
DayArray.Add(new {
id = i,
title = temp.County.ToString()
});
i++;
}

谢谢!

编辑:忘记提及实体来自 View ,考虑到关于主键的评论,这是有道理的。

最佳答案

您是否可能错误配置了主键,以至于 EF 认为某物是主键,而实际上每一行都具有相同的值?重要的是,EF 有义务在每次看到具有与之前看到的相同类型+主键的对象时为您提供相同的实例

所以如果你所有的记录都是这样的:

id   | title | ...
-----+-------+-------
1 | Foo | ...
1 | Bar | ...
1 | Baz | ...
...

如果 EF 认为 id 是主键,它每次都会返回相同的对象 - 所以您会看到 FooFoo , Foo...

关于c# - 迭代 LINQ 实体结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1019956/

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