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 empty, like this new Binary(new byte[] {}); but this is not an empty empty column. Is there a workaround for LinqToSql?

+4
source share
4 answers

Something else is happening to you. I just created a small sample table with id (identifier), null varbinary (MAX), non-nullable varbinary (MAX) and timestamp. Using the following code works fine, without 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, how does this code correctly throw (and catch) an 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 implementation of a class that has a SendPropertyChanging handler for a property that throws an ArgumentNullException?

EDIT : based on OP comment.

Note that you cannot assign a variable of byte type [] to the binary file directly, since it causes an implicit conversion operation and an implicit conversion will raise an ArgumentNullException. You must check if the value is null before trying to assign it, and just assign the value null if the byte [] variable is null. This seems like strange behavior to me, and I hope that they will change it in the future. The MSDN documentation indicates that some changes may occur in future versions.

+5
source

Are you sure the field is NULL in the database? Does the updated linq data model match? If you are using attribute-based matching, the [Column(...)] attribute must have CanBeNull=true .

+1
source

@tvanfosson (posted as answer for better code formatting)

Yes, you're right, something strange is happening, something in excess of my knowledge of C #.

from.ImageThumbnail is a byte [] to.ImageThumbnail is a binary

Using? or?? the operators will not work, if I just use it, if it still works, it's strange. I do not understand why: -)

  if (from.ImageThumbnail != null) // works { to.ImageThumbnail = from.ImageThumbnail; } else { to.ImageThumbnail = null; } to.ImageThumbnail = from.ImageThumbnail != null ? from.ImageThumbnail : null; // fails to.ImageThumbnail = from.ImageThumbnail ?? null; // fails 
+1
source

You can use the ExecuteQuery () method to pass your own SQL.

0
source

Source: https://habr.com/ru/post/1305013/


All Articles