Search code examples
c#linq-to-sqlvarbinary

Set Linq To Sql Binary field to null


Trying to set a Binary field to null gives me an ArgumentNull exception. I can set the field to be empty like this new Binary(new byte[] {}); but that's not null just an empty column. Is there a workaround using LinqToSql ?


Solution

  • You've got something else going on. I just created a small sample table with an id (identity), nullable varbinary(MAX), non-nullable varbinary(MAX), and timestamp. Using the following code works just fine with no errors.

    using (var context = new TestDataContext())
    {
        var binarySample = new BinarySample
        {
            Image = null,
            NonNullImage = new Binary( new byte[0] ),
        };
        context.BinarySamples.InsertOnSubmit( binarySample );
        context.SubmitChanges();
    }
    

    Where as this code properly throws (and catches) a SQLException, not an ArgumentNullException.

    try
    {
        using (var context = new TestDataContext())
        {
            var binarySample2 = new BinarySample
            {
                NonNullImage = null,
                Image = new Binary( new byte[0] )
            };
            context.BinarySamples.InsertOnSubmit( binarySample2 );
            context.SubmitChanges();
        }
    }
    catch (SqlException e)
    {
        Console.WriteLine( e.Message );
    }
    

    Is it possible that you have a partial class implementation that has a SendPropertyChanging handler for the property that is throwing the ArgumentNullException?

    EDIT: based on the OP's comment.

    Note that you can't assign a variable of type byte[] to the Binary directly as that invokes the implicit conversion operation and the implicit conversion will throw an ArgumentNullException. You should check if the value is null before attempting to assign it and simply assign null if the byte[] variable is null. To me this seems like odd behavior and I would hope that they would change it in the future. The MSDN documentation indicates that some change may occur in future versions.