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.
var personid = ctx.persons
.Where(p => p.login == currentLogin)
.Select(p => new {Prop = p.Column, personid = p.id})
.SingleOrDefault()?.personid;
Would probably work.