Simple way to return anonymous types (to make MVC using LINQ possible)

后端 未结 6 1956
囚心锁ツ
囚心锁ツ 2021-01-05 19:03

I\'d like to implement MVC while using LINQ (specifically, LINQ-to-entities). The way I would do this is have the Controller generate (or call something which generates) th

相关标签:
6条回答
  • 2021-01-05 19:10

    Use a view model layer. Your view has to know what it is going to display. I guess its possible to create a view that just formats a multi-dimensional array of data, but that isn't exactly the best reason to go with an MVC solution. You can however populate a view model with an anonymous object for consumption in your view.

    0 讨论(0)
  • 2021-01-05 19:18

    You can easily convert anonymous types into dynamic objects, here is the simple implementation of Donymous objects (Dynamic anonymous objects) that can populate from Anonymous object or DataReader.

    0 讨论(0)
  • 2021-01-05 19:19

    How about this?

    I assume that you have an entity class for your table 'myTable' (let's call it 'MyTableEntity'), so why don't you instantiate a new MyTableEntity object and use object initializer to fill only those columns you want?

    return (from o in myTable select new MyTableEntity { AColumn = o.column });
    

    This will not translate to a SELECT * as you asked, but you'll still have a way to pass a strongly-typed object to a view.

    You have to be careful to just make use of the initialized properties inside the view and that's it.

    Does this makes sense for you?

    0 讨论(0)
  • 2021-01-05 19:21

    On .NET 4.0 Anonymous types can easily be converted to ExpandoObjects and thus all the problems is fixed with the overhead of the conversion itself. Check out here

    0 讨论(0)
  • 2021-01-05 19:22

    Anonymous types are primarily designed to be used within a method. They are not suitable for communication between methods.

    If you need to pass a set of data between two functions the best way is to create a new type wrapping the data or use a loser grouping like Tuple<T1,T2> or KeyValuePair<TKey,TValue>

    0 讨论(0)
  • 2021-01-05 19:36

    Since no one even attempted to answer my question, I will answer it myself..

    It turns out, C# 4.0 supports duck-typing - they call it dynamic typing. However, in using dynamic types to return anonymous types, we lose the benefits of strong types:

    • Compile-time type-checking
    • Performance
    • Intellisense

    I've opened a feature request to have strongly-typed anonymous return types here - if you think this would be a useful addition to C# 5, follow the link and let the .Net team know!

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