我尝试使用LINQ从3个表中获取数据以返回IEnumerable<PortalUser>
但没有太多运气。当我想要返回结果时,它的类型为IQueryable<PortalUser>
,我不确定为了达到目标我应该做些什么:
public Task<IEnumerable<PortalUser>> GetUsers(string accountCode)
{
var res = from u in _db.Users
join ur in _db.UserRoles on u.ContactGuid equals ur.ContactGuid
join r in _db.Roles on ur.RoleId equals r.Id
where ur.AccountCode == accountCode
select(new PortalUser(u.Id, u.FriendlyName, u.UserName, r.RoleName));
return res;
}
在我的选择中,我尝试使用PortalUser
构造函数来制作PortalUsers,并认为这会给我我想要的但显然没有。
public class PortalUser
{
public PortalUser(int id,string friendlyName,string username,string rolename)
{
Id = id.ToString();
Firstname = friendlyName.Split(' ')[0];
Lastname = friendlyName.Split(' ')[1];
Username = username;
Role = rolename;
}
public string Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Username { get; set; }
public string Role { get; set; }
}
我收到此错误:
无法将
'System.Linq.IQueryable<BSAR.Services.Models.Outbound.Full.PortalUser>'
类型隐式转换为'System.Threading.Tasks.TaskSystem.Collections.Generic.IEnumerable<BSAR.Services.Models.Outbound.Full.PortalUser'>
。存在显式转换(您是否错过了演员?)
答案 0 :(得分:1)
执行CodeCaster建议&#34;您可以更改返回类型吗?如果没有,为什么不标记方法async并返回await res.ToListAsync()?你真的想做什么?&#34;
public async Task<IEnumerable<PortalUser>> GetUsers(string accountCode)
{
var res = from u in _db.Users
join ur in _db.UserRoles on u.ContactGuid equals ur.ContactGuid
join r in _db.Roles on ur.RoleId equals r.Id
where ur.AccountCode == accountCode
select (new PortalUser(u.Id, u.FriendlyName, u.UserName, r.RoleName));
return await res.ToListAsync();
}
这解决了我的问题谢谢
答案 1 :(得分:0)
GetUsers
不会返回任务 - 因此您必须将返回类型更改为IEnumerable<PortalUser>
:
public IEnumerable<PortalUser> GetUsers(string accountCode)
{
var res = from u in _db.Users
join ur in _db.UserRoles on u.ContactGuid equals ur.ContactGuid
join r in _db.Roles on ur.RoleId equals r.Id
where ur.AccountCode == accountCode
select (new PortalUser(u.Id, u.FriendlyName, u.UserName, r.RoleName));
return res;
}