Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post Dec 28, 2012 09:07 PM by AceCorban
Dec 28, 2012 05:35 PM|LINK
New to all this and trying to work out what's wrong with the following...
xxxSession = db.vwUserXXXSessions.Where(v => v.UserID == uid);
I get the error message that Error 1 Cannot implicitly convert type 'System.Linq.IQueryable<MyWebsiteModel.Models.vwUserXXXSession>' to 'MyWebsiteModel.Models.vwUserXXXSession'. An explicit conversion exists (are you missing a cast?)
Dec 28, 2012 06:16 PM|LINK
use "SingleOrDefault". Where returns an IQueryable List of objects, it looks like you want a single object:
vwUserXXXSession xxxSession = db.vwUserXXXSessions.SingleOrDefault(v => v.UserID == uid);
It is worth noting that this only works if v.UserID is unique, otherwise SingleOrDefault will throw exceptions if it finds more than one. In cases like that, you can try FirstOrDefault.
Also note that this will return null if no item is found.
Dec 28, 2012 07:50 PM|LINK
The table is a SQL server view and I do want it to return more than one entry. In this case how would I re-word it?
As for the null - I'm taking baby steps -- will get the basic working first then put in error handlers for nulls.
Dec 28, 2012 07:55 PM|LINK
Actually I suppose the answer would therefore be:
xxxSession = db.vwUserxxxSessions.Where(v => v.UserID == uid);
(the word session in this context is nothing to do with Asp.net sessions, it's just something else in my website)
Dec 28, 2012 09:07 PM|LINK
Yeah, you are on the right track. Just read the error message and see what it is telling you. It is saying that you can implicitly convert between an IQueryable collection of an object (which is what is returned from the .Where() method) to an object instance
(which is what you set the variable type to be). To think of it simpler, it is the same error you'd get if you did something like this:
int counter = "0";
If you want a full collection, just change the type of your variable:
IQueryable<vwUserxxxSession> xxxSessions = db.vwUserxxxSessions.Where(v => v.UserID == uid);
Another thing to consider is to have it return a List instead. People like to do this to enforce separation of concerns so that whatever business logic that is making a call to the function that returns the data can't continue to do database operations on it. Think of an IQueryable as a database query in progress. You can continue to manipulate it until you somehow process the data. This can add overhead. This is actually up to you. I use a repository pattern, but still return IQueryables because I have custom objects that extend my datamodel that sometimes needs to modify the returned query. However, if you just need the data, it is considered a best practice and you can do so like this:
List<vwUserxxxSession> xxxSessions = db.vwUserxxxSessions.Where(v => v.UserID == uid).ToList();