迭代LINQ实体结果

时间:2009-06-19 20:43:21

标签: c# linq entity-framework

我认为这是一段非常简单的代码,但结果令我感到困惑。我正在使用LINQ查询实体,然后迭代结果以创建数组。我正在观察进出数据库的流量,一切看起来都不错。当我复制LINQ发送到SQL的查询并直接针对SQL运行时,我得到了预期的结果。但是,当我迭代结果 - 或者甚至监视结果时 - 每个记录都是完全相同的。这是 NOT 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++;
 }

谢谢!

编辑:忘了提到实体来自一个视图,这对于主键的评论是有意义的。

1 个答案:

答案 0 :(得分:7)

您是否错误配置了主键,以至于EF认为某些内容是主键,而实际上每行具有相同的值?重要的是,EF每次看到与之前见过的类型+主键相同的对象时,都必须为您提供相同的实例

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

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

如果EF认为id是主键,则每次都会返回相同的对象 - 因此您会看到FooFoo,{{1} } ...

相关问题