我有以下 linq 查询...
public List<UserProject> GetProjectsByUser(int userid)
{
//var query =
return (
from p in this.Entities.Projects
join c in this.Entities.Categories
on p.CategoryId equals c.CategoryId
join u in this.Entities.Users
on p.UserId equals u.UserId
where p.UserId == 11
select
new
{
p.ProjectId,
u.UserName,
p.UserId,
ProjectName = p.Name,
ProjectDescription = p.Description,
CategoryName = c.Name
}
into pcup
join m in this.Entities.Messages
on
pcup.ProjectId equals m.ProjectId
into pm
select
new {
pcup.ProjectId,
pcup.UserId,
pcup.ProjectName,
pcup.ProjectDescription,
Messages = pm
}
).ToList<UserProject>();
}
我有以下 View 对象,我正在尝试填充......
public class UserProject
{
UserProject()
{
Messages = new EnumerableQuery<Message>();
}
public int ProjectId;
public int UserId;
public string ProjectName;
public string ProjectDescription;
public IEnumerable<Message> Messages;
//public string UserName;
//public string CategoryName;
//public int CategoryId;
}
一个项目上可能有 0 条消息。我的目标是将 UserProject 对象列表传递到我的 MVC View ,每个 UserProject 对象可以有一个消息集合。我得到的错误如下
Error 1 Instance argument: cannot convert from '
System.Linq.IQueryable<AnonymousType#1>
' to 'System.Collections.Generic.IEnumerable<Riebro.Services.UserProject>
'Error 2 '
System.Linq.IQueryable<AnonymousType#1>
' does not contain a definition for 'ToList
' and the best extension method overload 'System.Linq.Enumerable.ToList<TSource>(System.Collections.Generic.IEnumerable<TSource>)
' has some invalid arguments
目前消息实体没有项目的导航属性...它应该...我稍后会添加该更改...但目前我只需要继续工作。
编辑
现在 linq 查询看起来像这样......
return (
from p in this.Entities.Projects
join c in this.Entities.Categories
on p.CategoryId equals c.CategoryId
join u in this.Entities.Users
on p.UserId equals u.UserId
where p.UserId == userid
select
new
{
p.ProjectId,
u.UserName,
p.UserId,
p.Name,
p.Description,
//CategoryName = c.Name
}
into pcup
join m in this.Entities.Messages
on
pcup.ProjectId equals m.ProjectId
into pm
select
new UserProject {
ProjectId = pcup.ProjectId,
UserId = pcup.UserId,
ProjectName = pcup.Name,
ProjectDescription = pcup.Description,
Messages = pm
}
).ToList<UserProject>();
View 类看起来像这样......
public class UserProject
{
public UserProject()
{
Messages = new List<Message>();
}
public int ProjectId;
public string UserName;
public int UserId;
public string ProjectName;
public string ProjectDescription;
public List<Message> Messages;
//public string CategoryName;
//public int CategoryId;
}
我现在收到以下错误...
Error 1 Cannot implicitly convert type '
System.Collections.Generic.IEnumerable<Riebro.Message>
' to 'System.Collections.Generic.List<Riebro.Message>
'. An explicit conversion exists (are you missing a cast?)
最佳答案
您应该在 select 语句中创建一个 UserProject 实例而不是匿名对象。
select new UserProject
{
ProjectId = pcup.ProjectId,
UserID = pcup.UserId,
ProjectName = pcup.ProjectName,
ProjectDescription = pcup.ProjectDescription,
Messages = pm
}
关于linq查询匿名类型无法转换为POCO对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9353391/