My Technical Notes

Tuesday, 4 May 2010

Linq Exception: The null value cannot be assigned to a member with type System.Guid which is a non-nullable value type.

This exception is caused when you have a Guid Property (non-nullable) in the LINQ dbml file, but in reality, in the the SQL Server database, this Guid field actually allows NULL values.

For example, in my LINQ DBML I had a table defined called Resource which had a System.Guid property called TeamId. However, the SQL Server field [dbo].[Resource].[TeamId] allowed NULL values.

The reason why this exception occurs is because when LINQ retrieves a [dbo].[Resource] row, it creates a new Resource object and tries to assign the TeamId property the value of the [TeamId] SQL field. If the [TeamId] SQL field is NULL, then it will throw an Exception because it cannot assign NULL to the non-nullable TeamId property on the Resource object.

The fix in this case is to open the DBML file and, on the TeamId's properties, set Nullable to True.

1 comment:

oivoodoo said...

Hi,

Do you know how to fix this problem?
I have to clear this field after some operations. But it impossible. I try to write Guid.Empty, but my contraints not allowed to make it. Do you know any possible ways to make it?

regards,
Alexander.