Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL Design question

Often I need to combine data from multiple tables and display the result in a GridView control.

I can write a Linq query inline in the Page_load event, return an anonymous type that combines all the fields that I need, and databind the result to the GridView control.

  • Problem: I use 'helper methods' as described by Scott Guthrie on his blog. Such a helper method cannot return an anonymous type. The query would have to be inline for this approach.

I can write a database view that returns the data that I need, and write a helper method with a query against this (new and known) type that it returns.

  • Problem: I will need a lot of views in my database schema, and I will introduce a lot of redundant aspects of my data. I also lose some of the advantage of using Linq - removing all business logic from the database.

I would like to take an approach that lets me keep the Linq queries in helper methods, yet allows me to access all the attributes that I need on the grid in their respective databinding expressions. Can this be done?

like image 488
cdonner Avatar asked Nov 15 '22 14:11

cdonner


1 Answers

I asked the wrong question, as I frequently do. What prompted me to look into anonymous types was an apparent limitation of the GridView - my inability to use a databinding expression in an <asp:BoundField> (the DataField parameter only accepts column names of the table that the Linq query pulls in).

Turns out that in a TemplateField it is possible to use Eval and access members of the Linq data item, and Linq takes care of the query for me. In other words, I can keep the query in my helper method, have it return a primary database table type (e.g. Account), and I bind the Accounts to the GridView. In the databinding expressions I can access data members of the Account objects that reside in other tables, without having to explicitly pull them in in the query. Perfect.

like image 181
cdonner Avatar answered Dec 10 '22 21:12

cdonner