James Wilson
James Wilson

Reputation: 5150

LINQ Weirdness with joining tables

I have to join multiple tables. The tables have similar data for each table.

ID
(table id for FK)
Name
Description
Owner

from d in Departments
join f in Functions on d.DepartmentID equals f.DepartmentID
join pg in Processes on f.FunctionID equals pg.FunctionID
select new { d.DepartmentID, f.Name, pg.Name }

This throws an error 'An anonymous type cannot have multiple properties with the same name'

is there a better way to join these tables?

Should I do Select new { d, f, pg } ? Is it easy to grab the data from that?

I am very new to LINQ so any help is appreciated.

Upvotes: 1

Views: 63

Answers (2)

dlev
dlev

Reputation: 48596

You just need to give unique names for the two Name properties. Something like:

from d in Departments
join f in Functions on d.DepartmentID equals f.DepartmentID
join pg in Processes on f.FunctionID equals pg.FunctionID
select new { d.DepartmentID, FName = f.Name, PGName = pg.Name }

When you don't specify your own names, the compiler will just use the full name of the property, but since in this case they are both just Name, it will generate an error.

Upvotes: 3

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

The compiler creates the properties of the anonymous type based on the property you use. In your case you use the property Name twice. Once in f.Name and once in pg.Name.
To fix it you have to specify at least one of the two property names explicitly:

select new { d.DepartmentID, FunctionName = f.Name, ProcessName = pg.Name }

Upvotes: 3

Related Questions