LINQ Error InvalidCastException

I get a "InvalidCastException" (occurred in System.Data.Linq.dll) in my function:

public User GetUserByKey(Guid key)
{
            return usersTable.FirstOrDefault(m => m.UserKey == key);
}

which is called here:

MembershipUser mu = Membership.CreateUser(user.UserName, user.Password, user.Email, null, null, true, Guid.NewGuid(), out status);
User new_user = _UsersRepository.GetUserByKey((Guid)mu.ProviderUserKey);

mu.ProviderUserKey is a Guid object encapsulated in a generic object type, so everything should be fine: /

Thank you for your help!

+3
source share
4 answers

Since you mentioned earlier nvarchar(100)in your comment, try the following:

Guid key = new Guid(mu.ProviderUserKey.ToString()); // object to string
User new_user = _UsersRepository.GetUserByKey(key);

In addition, SQL Server has a unique identifier data type to represent a GUID that you can use .

+1
source

(User ).

, , , , . , - , Linq .

- ProviderUserKey Guid - , Guid object, ( null, ). , ?

0

, , .

, , .

, .

0

A quick and easy way to talk about it; mouse over the field and make sure this is a guide. For security reasons, you might want to use Guid.TryParse to safely pass a value if its GUID is to prevent this error from occurring. It uses a string value in the base database, and I don't know if there is a built-in conversion, or if you need to convert using Guid.Parse or Guid.TryParse.

NTN.

0
source

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


All Articles