Reputation: 51064
I have the following T-SQL that replaces blank values with '[Unknown]'. How can I achieve this in a LINQ to EF query?
select distinct case when CostCentre = '' then '[Unknown]' else CostCentre end as CostCentre
Upvotes: 1
Views: 81
Reputation: 12768
I suspect that the best solution for you is in using an anonymous type in your select—i.e. you're creating a custom/calculated property in a one-off class situation. Selecting an anonymous type allows you to do this:
var items = from testItem in context.TestItems
select new { CostCentre = (testItem.CostCentre == "" ? "[Unknown]" : testItem.CostCentre) };
This will result in items being a custom IQueryable type where each item has a single property of CostCentre that is type string. If all you really want is the strings, you can end up with an IQueryable<string> if you simplify it thus:
var items = from testItem in context.TestItems
select testItem.CostCentre == "" ? "[Unknown]" : testItem.CostCentre;
I hope this helps. You'll have bigger complications if you want more than the one property, but this is a good starting point.
Upvotes: 1
Reputation: 8129
with a projection:
var result = ctx.Source.Where(...).Select(i => CostCentre == "" ? "Unknown" : CostCentre);
should give you a IQuerialable of strings.
Upvotes: 1