Error when using LINQ with anonymous classes and implicitly typed arrays in ASP.NET WebPages

后端 未结 1 808
旧时难觅i
旧时难觅i 2021-01-28 12:15

I am trying to mock up a page using WebMatrix using WebPages under the hood. I have assigned an implicitly typed array of anonymous objects to one of the PageData keys, but I ge

1条回答
  •  别那么骄傲
    2021-01-28 12:29

    The general solution to this problem is to explicitly cast it. i.e. Cast the expression PageData["Vals"] to an array of the type you expect. However, this cannot work with anonymous types because you don't have the handle to its type and therefore cannot cast it.

    Once you've stored your new[] { ... } in the dynamically typed PageData, you've lost all compile-time reference to the anonymous type. Therefore, trying to use type-specific LINQ operators on it is a non-starter.

    As I mentioned in the comments, the correct solution is to always use strongly-typed models. You should not be relying on anonymous types declared and defined within a view in order to mock up the page. Have the page depend on a real model and populate that model and feed it to the page.

    0 讨论(0)
提交回复
热议问题