Sql – Column.DbType affecting runtime behavior

linq-to-sqlnet

According to the MSDN docs, the DbType property/attribute of a Column type/element is only used for database creation.

Yet, today, when trying to submit data to an IMAGE column on a SQLCE database (not sure if only on CE), I got an exception of 'Data truncated to 8000 bytes'. This was due to the DbType still being defined as VARBINARY(MAX) which SQLCE does not support. Changing the type to IMAGE in the DbType fixes the issue.

So what other surprises does Linq2SQL attributes hold in store? Is this a bug or intended? Should I report it to MS?

UPDATE

After getting the answer from Guffa, I tested it, but it seems for NVARCHAR(10) adding a 11 char length string causes a SQL exception, and not Linq2SQL one.

The data was truncated while converting from one data type to another. 
     [ Name of function(if known) =  ]
A first chance exception of type 'System.Data.SqlServerCe.SqlCeException' 
     occurred in System.Data.SqlServerCe.dll

Best Answer

The DbType is only required if you are going to create a table, but that doesn't mean that it's ignored the rest of the time.

If you for example define a VarChar column with the size 100, you will get an exception if you send a string that is longer than 100 characters even if the field in the database actually could accomodate the string.

The documentation says that you shouldn't specify the DbType if it's not needed, as the data type is inferred from the value that you use. However, there might be some situations where you don't want it to use the DbType that is inferred.

Related Topic