为什么Linq to Entity Select Method翻转投影列表属性?

时间:2013-02-25 21:00:10

标签: c# asp.net-mvc json entity-framework linq-to-entities

我对linq to entity / Json / MVC.net 4有最奇怪的行为

我有这些代码,并且由于一些奇怪的原因,每个其他列表的属性顺序都是相反的。

var output = db.FooBar.Where(a => a.lookupFoo == bar)
                      .Select(a => new List<double>{
                                     //value's are the same per row 
                                     //for demonstration sake.
                          a.fooBarA,  //Always 12.34
                          a.fooBarB,  //Always 12.34
                          a.fooBarC,  //Always 0
                          a.fooBarD  //Always 0 //lazy casting to double from int
                      });
return Json(new {output});

输出如下:

{
  "output": [
    [12.34, 12.34, 0,     0], 
    [0,     0,     12.34, 12.34], 
    [12.34, 12.34, 0,     0],
    [0,     0,     12.34, 12.34]
  ]
};

我设法通过在Where和Select之间放置一个toList()来解决这个问题,但我仍然想知道为什么会发生这种情况。

更多信息: EF 4.4(tt生成上下文),SQL Server 2008r2表示.NET 4.0,MVC 3.0,Vanilla System.Web.Mvc.JsonResult,表由一个int主键组成,浮点数除去最后一个是int的值

2 个答案:

答案 0 :(得分:1)

尝试

var output = db.FooBar.Where(a => a.lookupFoo == bar)
                  .Select(a => new List<double>{
                                 //value's are the same per row 
                                 //for demonstration sake.
                      a.fooBarA,  //Always 12.34
                      a.fooBarB,  //Always 12.34
                      a.fooBarC,  //Always 0
                      a.fooBarD  //Always 0 //lazy casting to double from int
                  }).toList();
return Json(output);

在你的路上输出只是上下文生成的脚本获取数据 可能是大小Json()

的多次执行

答案 1 :(得分:0)

添加.ToArray,看看你得到了什么。请记住,linq(Select .. exc)仅在调用IEnumerator时执行。

我认为如果添加ToArray,每次结果都是一样的,并且一致。

希望有所帮助。