迭代LINQ实体结果

3 c# linq entity-framework

我认为这是一段非常简单的代码,但结果令我感到困惑.我正在使用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++;
 }
Run Code Online (Sandbox Code Playgroud)

谢谢!

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

Mar*_*ell 7

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

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

id   | title | ...
-----+-------+-------
1    | Foo   | ...
1    | Bar   | ...
1    | Baz   | ...
...
Run Code Online (Sandbox Code Playgroud)

如果EF认为id是一个主键,它会每次给你回相同的对象-所以你会看到Foo,Foo,Foo...