Explain Codes LogoExplain Codes Logo

Data is Null. This method or property cannot be called on Null values

csharp
nullable-reference-types
entity-framework
null-coalescing-operator
Anton ShumikhinbyAnton Shumikhin·Sep 12, 2024
TLDR

The quickest way to deal with a "Data is Null" error is to use SQL's built-in COALESCE() function, which replaces NULLs with a default value:

SELECT COALESCE(myColumn, 'Default') FROM myTable;

Voilà! Non-null results for all rows, null-related catastrophes averted.

Learning to C#-the Nulls

Maintenance nightmare? Verify your models in C# match your database neighbour:

public class Movie { public int Id { get; set; } public string? Genre { get; set; } // Nullable string? I didn't see it coming! }

C# 8 nullable feature is your new best buddy, embrace it with open arms in your .csproj file:

<PropertyGroup> <Nullable>enable</Nullable> </PropertyGroup>

We have just stepped into a null-free wonderland.

Guardians of the Schema

Remember, SQL schema is the law; neglect can lead to data misdemeanors. Keep the fields that could be null as nullable:

ALTER TABLE myTable ALTER COLUMN myColumn VARCHAR(100) NULL; // You have the right to be NULL!

ISNULL function is also here to preserve law and order:

SELECT ISNULL(myColumn, 'Default') FROM myTable; // Null, we’ve got you covered!

Coping nulls: Stored procedures edition

Introduce aliases in stored procedures to keep null blues at bay:

CREATE PROCEDURE GetMovieGenre @MovieID INT, @Genre NVARCHAR(100) OUTPUT AS BEGIN SELECT @Genre = ISNULL(Genre, 'No Genre') FROM Movies WHERE Id = @MovieID; // In genre we trust! END

Null Checks and Swaps: SQL Edition

Up your SQL game by learning null check:

SELECT myColumn FROM myTable WHERE myColumn IS NOT NULL;

And null swap:

SELECT NULLIF(myColumn, 'ValueToBecomeNull') FROM myTable;

Don't let the NULLs get you, you got them!

Use null-coalescing operator (??) in C# to assign default if a value is NULL:

public void PrintGenre(Movie movie) { string genre = movie.Genre ?? "No Genre"; // Who said nulls ain't fun? Console.WriteLine(genre); }

Null Handling: EF Models Style

To tackle NULL woes, marry your Entity Framework models with the field properties of your tables. Bid adieu to .IsRequired(), if field can be null:

modelBuilder.Entity<Movie>() .Property(b => b.Genre) .IsRequired(false); // Genre-ously nullable

Application Logic Level: Null Combat

Smart defaults can null-proof your application logic:

if (movie.Genre == null) { movie.Genre = "Unknown Genre"; // Mission: Null Impossible! }

Managing the NULLStorm: Advanced Techniques

Protect your code from NULLStorms:

  • Arm yourself with unit tests for null cases
  • Be the first one to manage null return values
  • Win the war with nullable reference types