Linq.How to complete this query?

S

shapper

Hello,

I have 3 tables with a many to many relationship:

Professors > ProfessorID, Age, ...
Tags > TagID, Name, ...
ProfessorsTags > ProfessorID, TagID

How can I get all the professors and all tags associated to each
professor using LINQ?

I have the following:

List<ProfessorPaper> papers = (from p in database.Professors
orderby p.Name
select new ProfessorPaper {
Professor = p,
Tags = new List<Tag> {

}
}
}).ToList();

ProfessorPaper is a wrapper that contains two properties: Professor
and List<Tag>.
In my query what I am missing is filling the tags for each professor.

Could someone, please, tell me how to do this?

Thanks,
Miguel
 
J

Jon Skeet [C# MVP]

Hello,

I have 3 tables with a many to many relationship:

Professors > ProfessorID, Age, ...
Tags > TagID, Name, ...
ProfessorsTags > ProfessorID, TagID

How can I get all the professors and all tags associated to each
professor using LINQ?

I have the following:

      List<ProfessorPaper> papers = (from p in database.Professors
                                          orderby p.Name
                                          select new ProfessorPaper {
                                            Professor = p,
                                            Tags = new List<Tag> {

                                            }
                                          }
                                          }).ToList();

ProfessorPaper is a wrapper that contains two properties: Professor
and List<Tag>.
In my query what I am missing is filling the tags for each professor.

Could someone, please, tell me how to do this?

Well, you could try:

Tags = from pt in database.ProfessorsTags where pt.Professor == p
select pt.Tag

I don't know how nicely that will translate into SQL though.

Alternatives will depend on how you've mapped the ProfessorsTags
collection. For instance, if you've got two many-to-one relationships
mapped, and you've made both of them bidirectional, you may be able to
do:

Tags = p.ProfessorsTags.Tags

Again, I don't know offhand what the SQL for this would look like.

Jon
 
S

shapper

Well, you could try:

Tags = from pt in database.ProfessorsTags where pt.Professor == p
select pt.Tag

I don't know how nicely that will translate into SQL though.

Alternatives will depend on how you've mapped the ProfessorsTags
collection. For instance, if you've got two many-to-one relationships
mapped, and you've made both of them bidirectional, you may be able to
do:

Tags = p.ProfessorsTags.Tags

Again, I don't know offhand what the SQL for this would look like.

Jon

Thanks Jon. I will try it
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top