Hi im trying to assign a default group to any user that registers with my site. Since the admin Id of that group is the administrator, I query my database for a group with a admin id of my administrator and then assign that group to the user. However the following error is being thrown
“Unable to cast object of type ‘System.Data.Objects.ObjectQuery`1[DatabaseModel1.Group]’ to type ‘DatabaseModel1.Group’. ”
Heres the code
Dim defaultGroup = (From group As Group In context.Groups
Where group.AdminID = ((From users As User0 In context.User0
Where users.Name Like "Administrator"
Select users.UserID).First)
Select group)
currentUser.Groups.Add(defaultGroup)//the error is being thrown here
any help would be appreciated
Thanks
It sounds like you’ve got a query which can return multiple results, but you’re trying to assign it to a single-value variable.
You probably just need to use something like:
The probable options are:
First()– allows multiple results and returns the first; will throw an exception if there are noneFirstOrDefault()– allows multiple results and returns the first; will return the default value for the element type (e.g.null) if there are no resultsLast()– allows multiple results and returns the last; will throw an exception if there are noneLastOrDefault()– allows multiple results and returns the last; will return the default value for the element type (e.g.null) if there are no resultsSingle()– expects exactly one result; if there are no results or mulitple results, an exception is thrownNow that you’ve shown the query, it sounds like you should probably use a join rather than a nested query. I’m not hot on the VB query syntax, but in C# you might want: