0

In MVC we can declare nullable ints in our database context models as

public int? SomeField { get; set; }

But how do you check if a record for SomeField is Null in Linq. For example if I want to get a list of rows with value not zero I use the following Linq statement.

var k = db.TableSet.Where( u => u.Somefield != 0 )

Is there a Linq equivalent to include/exclude either/both Zeros and Null?

Edit: I am currently testing this but I am sure it will either be Null exception or Null fields return as zero.

2
  • Are you talking about null in SQL - the DBNull - or are you talking about a .NET null? Commented Aug 27, 2013 at 21:34
  • @KirkBroadhurst I need to check for DBNulls and then translate that into my class accordingly to prevent Null exceptions. Commented Aug 27, 2013 at 21:36

4 Answers 4

3

Personally I would prefer to filter out the null values in my data layer to prevent this kind of null checking in code.

BUT, you could use:

var k = db.TableSet.Where(u => u.Somefield.HasValue && u.SomeField != 0)

//Or

var k = db.TableSet.Where(u => u.Somefield != null && u.SomeField != 0)

//Or

var k = db.TableSet.Where(u => u.Somefield.GetValueOrDefault() != 0)

//Or

var k = db.TableSet.Where(u => (u.Somefield ?? 0) != 0)
Sign up to request clarification or add additional context in comments.

Comments

2

Sure:

var k = db.TableSet.Where( u => u.SomeField != null && u.Somefield != 0 )

or for a nullable type:

var k = db.TableSet.Where( u => u.SomeField.HasValue && u.Somefield != 0 )

Comments

1

You can do this:

var k = db.TableSet.Where( u => u.Somefield.HasValue && u.Somefield.Value != 0 )

Or this:

var k = db.TableSet.Where( u => u.Somefield != null && u.Somefield != 0 )

Or possibly this:

var k = db.TableSet.Where( u => (u.Somefield ?? 0) != 0 )

2 Comments

LINQ providers may choke on the second option.
Unbelievable, almost the same answer!
1

Yes; just compare to null.

If you want to exclude both, you'll need an and clause.

2 Comments

The problem with this Int types are not nullable in C#
@Flood: Your model should closely match your DB model. If it's possible that a column can be null, you need to make sure your model's corresponding property can be null as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.