Pradeep H
Pradeep H

Reputation: 613

Entity Framework - Select Single Column with Null Check

Trying below query to select value from single column in Entity Framework, but it is throwing exception when ColumnA is having Null value.

string test = dbContext.TABLE.Where(p => p.A== A).Select(x => x.ColumnA).SingleOrDefault().ToString();

I want to select some default value or assign null to string test if ColumnA is Null.

Upvotes: 0

Views: 2881

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

If using C# 6.0 or higher Use the ?. operator:

string test = dbContext.TABLE.SingleOrDefault(p => p.A == A)?.ColumnA.ToString();

If prior to C# 6.0 you can:

var columnA = dbContext.TABLE.Where(p => p.A == A).Select(x => x.ColumnA).SingleOrDefault();
string test = columnA == null ? null : columnA.ToString();

Upvotes: 1

Related Questions