Skip to content

NullReferenceException thrown when DbString instance is null #1425

@LanceRomance

Description

@LanceRomance

I found when calling a stored procedure that has a DbString property and that instance is null, a NullReference exception is thrown.

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at ParamInfo5dd7247d-fd49-42a6-8b6e-f45fb45c461e(IDbCommand , Object )
   at Dapper.CommandDefinition.SetupCommand(IDbConnection cnn, Action`2 paramReader)
   at Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition& command, Action`2 paramReader)
   at Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition& command)
   at Dapper.SqlMapper.Execute(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Nullable`1 commandTimeout, Nullable`1 commandType)
   at ConsoleApp1.Program.Main(String[] args)

Example:

using (var conn = new SqlConnection(connString))
{
	DbString nullDbString = null;
	var parameterObject = new
	{
		Value1 = nullDbString,
	};
	
	conn.Execute("Test_Insert", parameterObject, null, null, CommandType.StoredProcedure);
}

I bumped into this due to code that looked something like:

public class Model
{
	public string Value { get; set; }
}
public class Model2
{
	public Model Instance { get; set; }
}

public static class Extensions
{
	public static DbString ToDbString(this string value)
	{
		return new DbString() { Value = value };
	}
}
var model2 = new Model2();
model2.Instance = null; //null due to a missing model in a json payload or something

using (var conn = new SqlConnection(connString))
{
	var p = new
	{
		Value1 = model2?.Instance?.Value, //this is fine
		Value2 = model2?.Instance?.Value?.ToDbString() //this causes a null ref to be thrown
	};
	
	conn.Execute("Test_Insert", p, null, null, CommandType.StoredProcedure);
}

I would expect the same behavior as passing a null string - a conversion to DbNull.Value.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions