tags:

views:

16

answers:

1

What would be the best way to set a gridView.DataSource for LINQ query with some foreign keys and get fields in the parent tables? Like this:

The table BOOK have a Author_Id, which is related to table Author

class:

public IQueryable<Book> ListAll()
{
    RENDBDataContext db = new RENDBDataContext();
    var result = from b in db.Books
                 orderby b.Id descending
                 select b;
}

code-behind:

grdBooks.DataSource = vBooks.ListAll();
grdBooks.DataBind();

In the ASPX page I can get to the Author name with the [asp:TemplateField], using <%Eval("Author.Name")%>

What I'm looking for is a better solution, that doesn't involve changes in the aspx page

+2  A: 
var result = from b in db.Books 
             orderby b.Id descending 
             select 
             {
                 AuthorName = b.Author.Name,
                 Title      = b.Title,
                 etc        = b.etc
             };

Alternately, if you don't want to re-list every property you are going to use you could use:

var result = from b in db.Books 
             orderby b.Id descending 
             select 
             {
                 AuthorName = b.Author.Name,
                 Book       = b
             };

But then you'd have to write "Book.Title" in you r GridView. However, either way, it will get all the field you need in a single SQL statement.

James Curran
you missed the "new" keyword in select new {}. But I don't want to do it this way, as this would give me Anonymous types on my class-project, OR I would have to create a new class/datatype for every query like that
Vitor Reis
He also needs to figure out what he is passing back, he would have to pass back either `IQueryable<object>` or `IQueryable<dynamic>`, because he can't pass anonymous types through method boundaries as `var`.
Matthew Abbott