InvalidCastException: Unable to Cast SqlString to SqlGuid

asp.net-core c# entity-framework-core

Question

I feel like I'm losing my mind, why is this resulting in an InvalidCastException?

using (var dbContext = CreateDbContext()) 
{
    result = dbContext
            .Users
            .Where(m => m.UserId.Equals(userId)).SingleOrDefault();
}

In this case, "UserId" is a uniqueidentifier in SQL Server. userId is a System.Guid.

UserId on the C# in the DbSet is also a System.Guid.

Where is it getting SqlString from?

System.InvalidCastException: 'Unable to cast object of type 'System.Data.SqlTypes.SqlString' to type 'System.Data.SqlTypes.SqlGuid'.'

1
1
11/28/2019 4:20:39 PM

Accepted Answer

Be careful that your entity class fully matches the database definition.

In my case, columns were being matched in order, and some of those in the SQL table were not defined in the C# entity class.

0
11/28/2019 1:36:25 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow