By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,564 Members | 1,672 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,564 IT Pros & Developers. It's quick & easy.

LINQ: Related objects

P: n/a
Hi,

I have two classes (Review and Author) that are representative of tables
in my database. Both classes are marked up LINQ mappings. The database
(and classes) is structured in such a way that each Review has the ID of
the Author that wrote it, eg

[Table(Name = "Authors")]
public class Author
{
...
[Column(Name = "id", IsPrimaryKey = true, IsDbGenerated = true)]
public int ID
{
...
}
...
}

[Table(Name = "Reviews")]
public class Review
{
...
[Column(Name = "author")]
public int AuthorID
{
...
}
...
}

In the database, the "author" column in the "Reviews" table is a foreign
key mapped to the primary key (ID) of the "Authors" table.

What I am doing at the moment is getting an array of Review objects
using LINQ, and then looping through the array using a foreach
statement, then doing another query to get the Author object for each
Review, eg.

Review[] reviews = _db.GetReviews();
foreach (Review review in reviews)
{
Author author = _db.GetAuthorByID(review.AuthorID);
...
}

Now this to me seems awfully inefficient as it's going to doing loads of
queries to the database! Which brings me to my question - how can I do
this sort of thing in a more efficient way?

Can it be done keeping the Review and Author objects separate, or am I
going to have to create some sort of class that has all the information
about a review, ie. the review and author information? If so, how do I
go about writing a LINQ query to do this?

Thanks,

--
Dylan Parry
http://electricfreedom.org | http://webpageworkshop.co.uk

The opinions stated above are not necessarily representative of
those of my cats. All opinions expressed are entirely your own.
Jun 27 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Marc Gravell wrote:
You can express relations in LINQ via AssociationAttribute, and then
just navigate in the query; but setting these up correctly isn't
trivial; I'd suggest using the designer and seeing what it generates...
Thanks. I'll take a look into that.

--
Dylan Parry
http://electricfreedom.org | http://webpageworkshop.co.uk

The opinions stated above are not necessarily representative of
those of my cats. All opinions expressed are entirely your own.
Jun 27 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.