How to Select subset of columns from SingleOrDefault LINQ query in EF

c# entity-framework entity-framework-6 linq

Question

How can I select subset of all columns while using SingleOrDefault query? For example, following LINQ expression

var personid = ctx.persons.SingleOrDefault(p => p.login == currentLogin)?.personid;

will compile into SELECT TOP 1 * FROM ... type of query. I would like to Select() only the columns I am interested in, e.g. statement producing SELECT TOP 1 personid, myColumn FROM ... under-hood.

Please note, that the question cannot possibly be duplicate of linked question. I am interested in context of Single/SingleOrDefault not generic solution for LINQ. Chaining .SingleOrDefault() with .Select() is not possible for apparent reasons: Single<T>returns single object of type T (or throws) which clearly does not implement IEnumerable<T> and cannot be Select()ed upon.

1
3
8/29/2017 10:14:51 AM

Accepted Answer

var personid = ctx.persons
    .Where(p => p.login == currentLogin)
    .Select(p => new {Prop = p.Column, personid = p.id})
    .SingleOrDefault()?.personid;

Would probably work.

3
9/20/2017 7:14:01 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow