I have this code:
public static List<object> GetInbox(Guid id)
{
using (Flirt4dateDBDataContext dc = new Flirt4dateDBDataContext())
{
List<object> query = from pm in dc.PrivateMessages
join user in dc.Users
on pm.Sender equals user.UserID
select new
{
SenderName = user.Username
};
return query;
}
}
It is not working.
Error 1 Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.List'. An explicit conversion ex开发者_运维问答ists (are you missing a cast?) O:\Flirt4Date\Flirt4Date\DAL\PrivateMessageHandling.cs 69 29 DAL
So, what to do? I know, a possible Option is to write a Class and give back a List of that, but I have houndrets of query like this and I would be pleased if I can have a generic solution...
Change your code to :
List<object> query = (from pm in dc.PrivateMessages
join user in dc.Users
on pm.Sender equals user.UserID
select new
{
SenderName = user.Username
}).ToList();
or change your function to :
public static IEnumerable<object> GetInbox(Guid id)
{
using (Flirt4dateDBDataContext dc = new Flirt4dateDBDataContext())
{
IEnumerable<object> query = from pm in dc.PrivateMessages
join user in dc.Users
on pm.Sender equals user.UserID
select new
{
SenderName = user.Username
};
return query;
}
}
You're query is returning an IQueryable; you need to convert the result of your query into a List<> type, using the ToList operator
The value returned by the Linq query is of the type IQueryable, to convert that to a List you'll have to create a new List passing the object to the constructor.
Try this:
var result = from pm in dc.PrivateMessages ...
List<object> query = new List<object>(result);
... or use the ToList() extension method as suggested in the other responses.
you are returing a query variable and since Linq is based upon the deffered execution concept i.e. the query stored in the query variable will not eveluated until you call some iterator on this like (ToList(), ToDictionary() , toArray(), Count() etc..)
so chnage the code a little will work like this
public static List<object> GetInbox(Guid id)
{
using (Flirt4dateDBDataContext dc = new Flirt4dateDBDataContext())
{
List<object> query = (from pm in dc.PrivateMessages
join user in dc.Users
on pm.Sender equals user.UserID
select new
{
SenderName = user.Username
}).ToList();
return query;
}
}
Were you wanting to use deferred execution or did you want to run the query right away? If you want to defer execution return a IQueryable or IEnumerable else return a List.
If deferred be careful with the "using Flirt4dateDBDataContext dc = new Flirt4dateDBDataContext()
" block, it may dispose the datacontext before the query executes.
You could also use "var query
" instead of "List<object> query
" as the returned is actually not really a List<object>
精彩评论