Uniqueidentifier is null

Posted by AlexeyRusanov on 03-Apr-2014 06:27

I'm having the following issue with a null UniqueIdentifier:
I'm using MS SQL 2008, Framework 3.5


SQL setup:

create table Table1(Column1 uniqueidentifier)
insert into Table1 values(null)



C# code that fails:

DbProviderFactory factory = DbProviderFactories.GetFactory("DDTek.SQLServer");
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = @"Authentication Method=NTLM;Database Name=....;Host=....";
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "select Column1 From Table1";
var reader = command.ExecuteReader();
reader.Read();
var value = reader.GetGuid(0);



it fails on "reader.Read();" with the following error message: "Byte array for GUID must be exactly 16 bytes long.".

If Column1 is not Null, then it works alright.

Could you help me with this error, please?
Thanks!        

All Replies

Posted by Avadhoot Kulkarni on 03-Apr-2014 08:38

Hi,

As per the ADO.NET standard, The reader.getGuid() will throw the "InvalidCastException" if the value is null or DBNull.

msdn.microsoft.com/.../system.data.sqlclient.sqldatareader.getguid(v=vs.110).aspx

You can use reader.IsDBNull(0) to chek if the value is null and if not; then you can use the Specific type Accessor methods of DataReader class.

If you do not wish to use the IsDBNull() API; then you can replace the GetGuid() to GetValue() call; this returns the value (including null);

Hope this helps you resolve your error.

Posted by AlexeyRusanov on 26-May-2014 06:52

Hi,

Thanks for your help,

Yes, I see your point, however in my project I'm using Linq to Sql and when I drop that table onto the dbml designer, and execute this code:

DbProviderFactory factory = DbProviderFactories.GetFactory("DDTek.SQLServer");

DbConnection connection = factory.CreateConnection();

connection.ConnectionString = @"Server=...;Authentication Method=NTLM;Database Name=...";

connection.Open();

DataClasses1DataContext dc = new DataClasses1DataContext(connection);

dc.Table1s.First();

this fails with that very same error.

But if I use the regular sql provider (System.Data.SqlClient), it works fine.

Could you tell me how to fix this?

Thanks!

Posted by Avadhoot Kulkarni on 26-May-2014 07:03

Hi,

I see your point now. But, DataDirect Connect for ADO.NET providers do not support LINQ to SQL. Either you can use the normal ADO.NET Syntax to fetch the data or DAAB (Data Access Application Block)

This thread is closed