Randy Minder
Randy Minder

Reputation: 48402

Linq Query Help

I have the following Linq query:

from etamodule in ETAModule
join eta in ETA on etamodule.ExpID equals eta.ExpID
where etamodule.SubID==  "101106261013"
select new { etamodule }

ETAModule has a 1:1 relationship to ETA. However, there is not a FK in the database that enforces this (unfortunately). The way my query is constructed works fine, but I would like to include the ETA entity for each ETAModule entity, as a property of the ETAModule entity. Of course, this would be much easier if a FK existed. How can I modify my query to do this?

Thanks.

Upvotes: 0

Views: 55

Answers (1)

Joe Albahari
Joe Albahari

Reputation: 30934

You can include eta in the final projection most easily by adding it to the anonymous type:

from etamodule in ETAModule
join eta in ETA on etamodule.ExpID equals eta.ExpID
where etamodule.SubID==  "101106261013"
select new { etamodule, eta }

If you want eta to be a property of etamodule, you'll need to define a class that has this property, e.g., ModuleWithETA. You can then project as follows:

...
select new ModuleWithEta
{
  ID = etamodule.ID,
  Name = etamodule.Name,
  ...
  ETA = eta
}

If you want the equivalent of a left outer join (including all etamodules, regardless of whether they have an ETA), then change your query as follows:

from etamodule in ETAModule
where etamodule.SubID = "..."
select new
{
  etamodule,
  eta = ETA.FirstOrDefault (e => e.ExpID == etamodule.ExpID)
}

Upvotes: 1

Related Questions