The code:
var primeCtr = con.Contractors?.Where(ctr => ctr.Type == "Prime").FirstOrDefault();
if (primeCtr == null)
primeCtr = con.Contractors?.Where(ctr => ctr.Type == "Original Prime").FirstOrDefault();
Explanation: If a contractor of type "Prime" exists, use that one, else use the "Original Prime"
I could have coded this using ? : expression but I think it would have been less efficient?
var primeCtr = con.Contractors?.Where(ctr => ctr.Type == "Prime").Any() ? con.Contractors?.Where(ctr => ctr.Type == "Prime").FirstOrDefault() : con.Contractors?.Where(ctr => ctr.Type == "Original Prime").FirstOrDefault();
The query for "Prime" would get executed twice I think?
Just trying to determine if there is a more elegant way to express this using EF Core 8? This is my first EF Core app and I haven't used the old EF in several years, so could be rusty.
The most common way to do this is ordering by a predicate that expresses preference and take the first:
con.Contractors.OrderByDescending(ctr => ctr.Type == "Prime").FirstOrDefault()
If there are more types you'll have to filter out "Prime" and "Original Prime" (add a Where before the ordering).
The ordering is descending because then the one where ctr.Type == "Prime" is true floats to the top.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With