Using Entity Framework (LINQ to Entities)
The following is working just fine. The expressions got translated to SQL
var foos = ctx.Foos.Select(f => new {
P1 = ctx.Bars.FirstOrDefault(b => b.SomeProp == "Const1" && f.X1 == b.Y),
P2 = ctx.Bars.FirstOrDefault(b => b.SomeProp == "Const2" && f.X2 == b.Y),
P3 = ctx.Bars.FirstOrDefault(b => b.SomeProp == "Const3" && f.X3 == b.Y),
}
The repetitive expression b.SomeProp == "..." && f.X* == b.Y
is actually a simplified version of the real expression, but if you can help me wit this. I'll figure out the rest as well...
What I would like to write is something like this. (Preferred)
var foos = ctx.Foos.Select(f => new {
P1 = f.GetBar("Const1", f.X1),
P2 = f.GetBar("Const2", f.X2),
P3 = f.GetBar("Const3", f.X3),
}
But I might also be fine with something like
P1 = ctx.Bars.GetByFoo(f.X1, "Const1");
- or -
P1 = ctx.Bars.FirstOrDefault(GetByFoo(f.X1, "Const1"))
- or -
P1 = ctx.Bars.GetByFoo(x => x.X1, "Const1");
Based on this answer https://mcmap.net/q/731065/-how-does-one-use-a-custom-property-in-a-linq-to-entities-query The closest I came so far is
ctx.Bars.FirstOrDefault(GetByFoo(x => x.Y == f.X1 , "Const1"))
and
private static Expression<Func<Bar, bool>> GetByFoo(Func<Foo, bool> optionSelector, string par1)
{
return b => b.SomeProp == par1 && optionSelector(o);
}
Unfortunately, this a) Is still far from desired b) this does not work :(. It gives a run-time exception:
variable 'f' of type 'Foo' referenced from scope '', but it is not defined
It is essential that the expression keeps translatable. I am not fine with retrieving all foos and then retrieving the Bar for each foo.