I am new to using Linq Queries and I am trying to convert an IQueryable to a custom type but I am running into issues. See the code below; I've tried to add .ToList<>()
I've tried to use .Cast<>()
and nothing works. Any insight would be great.
Error: Cannot implicitly convert type
'System.Linq.IQueryable<string>'
to'System.Linq.IQueryable<eSTIP.Models.User>'
. An explicit conversion exists (are you missing a cast?)
private static List<UserViewModel> _allBCCUsers = null;
public static List<UserViewModel> AllBCCUsers
{
get
{
if (_allBCCUsers == null)
{
eSTIPContext ctx = new eSTIPContext();
IQueryable<User> users = from u in ctx.BBCRecipient select u.Email; //Error On this line
_allBCCUsers = new List<UserViewModel>();
foreach (User u in users)
_allBCCUsers.Add(new UserViewModel(u));
}
return _allBCCUsers;
}
}
The compiler explains exactly what is happening in your code.
With from u in ctx.BBCRecipient select u.Email
you are selecting only the Email
property from u
(users?) wich is a string and you are trying to store it in a IQueryable of type User .
Now you have two options: change your select to select u
(like @Holger said) or change to IQueryable<string>
but in this case you need more dramatic changes in your after code.
As I understand from your question, you want to return List of UserViewModel
that contains User
's those have Email
.
To do so you can select directly List<UserViewModel>
from LINQ without any iteration need:
private static List<UserViewModel> _allBCCUsers = null;
public static List<UserViewModel> AllBCCUsers
{
get
{
if (_allBCCUsers == null)
{
eSTIPContext ctx = new eSTIPContext();
_allBCCUsers = (from u in ctx.BBCRecipient select new UserViewModel(new User() { Email = u.Email })).ToList();
}
return _allBCCUsers;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.