开发者

Get field descriptions from a parent related table in a gridview

开发者 https://www.devze.com 2023-01-11 00:14 出处:网络
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:

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消