barjed
barjed

Reputation: 387

How to access ForeignKey values in GridView using LinqDataSource?

The problem is as follows:

I have three tables in database:

ARTICLE with fields like ID_Article, Title, etc. and also a FK ID_Author

CATEGORY with fields ID_Category, Name

CATEGORYTOARTICLE with fields ID_Article, ID_Category

Now I have a page that shows all Articles of a given Category. Inside there is a GridView.

        <asp:GridView ID="GridViewCategories" runat="server" 
            AutoGenerateColumns="False" DataSourceID="LinqSourceGridCategories" >
            <Columns>
                <asp:TemplateField>
                    <HeaderTemplate>Title</HeaderTemplate>
                    <ItemTemplate>
                        ???
                    </ItemTemplate>
                </asp:TemplateField>                        
            </Columns>
        </asp:GridView>

Plus a LinqDataSource

        <asp:LinqDataSource ID="LinqSourceGridCategories" runat="server" 
            ContextTypeName="konserwatyzm.db.DataClassesDataContext" EntityTypeName="" 
            TableName="CategoryToArticles" Where="ID_Category == @ID_Category">
            <WhereParameters>
                <asp:QueryStringParameter Name="ID_Category" QueryStringField="id" 
                    Type="Int32" />
            </WhereParameters>
        </asp:LinqDataSource>

The ID of the viewed Category is passed via QueryString.

How to access the fields of Article table so that I can create columns for them in GridView? I tried using Eval("Article.Title") but it keeps saying that "DataBinding: 'konserwatyzm.db.CategoryToArticle' does not contain a property with the name 'Article'."

Thanks!

Upvotes: 0

Views: 1555

Answers (1)

rah
rah

Reputation: 36

Make sure you have your keys defined correctly in your dbml or map. Then try constructing a query with the linqdatasource configuration wizard by selecting all the tables you want rows for. It looks like you only selected the CategoryToArticles table when you need it + the other two. You'll be able to reference the columns in the other tables that way.

Upvotes: 1

Related Questions