开发者

LINQ InvalidCastException error

I'm getting "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.P开发者_JS百科roviderUserKey);

mu.ProviderUserKey is the Guid object encapsulated in general object type so everything should be fine :/

Thanks for your help!


Since you mentioned it's a nvarchar(100) in your comment earlier try this:

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

Also, SQL Server has a uniqueidentifier data type to represent a GUID which you may consider using.


I might be off base here but you are creating a MembershipUser and from your method you are returning User.

Is this by design because if the two don't match then you'll get a cast error.

Try returning a MembershipUser and see if that helps.


An invalid cast exception is almost always due to an incorrect mapping in the destination class (User here).

Check the stack trace to see what the destination type is, which should help you narrow down which properties to look at. Most likely something changed in the database schema and the Linq entity wasn't updated.

Edit - the error could also be happening when casting ProviderUserKey to a Guid - you say it's a Guid boxed as an object but that might not be the case (it might be null, for example). Have you tried stepping in with a debugger and seeing what the actual runtime type is?


Quick and easy way to tell to figure it out; mouse over the field and ensure it's a guid. For safekeeping, you may want to consider using Guid.TryParse to safely pass the value if its a GUID, to prevent that error from happening. In the underlying database, it does use a string value, and I don't know if there is any in-built conversion, or if you need to convert using Guid.Parse or Guid.TryParse.

HTH.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜