我有两个表,分别是用户和歌曲。我需要在UserID列上加入它们并将列表返回给视图。我尝试写一个匿名类型,但我收到一个错误:
'LINQ to Entities中仅支持无参数构造函数和初始值设定项。'
我如何加入并返回列表?
public class User
{
[Key]
public virtual Guid UserId { get; set; }
[Required]
public virtual String Username { get; set; }
[Required]
public virtual String Email { get; set; }
[Required, DataType(DataType.Password)]
public virtual String Password { get; set; }
}
public class Song
{
public int SongId { get; set; }
public virtual Guid UserId { get; set; }
public string SongTitle { get; set; }
}
我尝试在这里实现类似这样的方法:
What is the return type of my linq query?
我最终得到的查询是:
var query = from u in db.Users
join s in db.Songs
on u.UserId equals s.UserId
select new HomeSongList(s.SongId, s.UserId, u.Username);
return View(query.ToList());
答案 0 :(得分:2)
错误信息很清楚,不是吗?
您尝试在linq2entity查询中创建一个新的HomeSongList(将在sql中翻译:不可能)
通过“用户属性”更正,您应该
var query = db.Songs.Select(s => new{
songId = s.SongId,
userId = s.User.UserId,
userName = s.User.Username})
.ToList()
.Select(x => new HomeSongList(x.songId, x.userId, x.userName);
或使用您的实际代码
var query = (from u in db.Users
join s in db.Songs
on u.UserId equals s.UserId
select new {
songId = s.SongId,
userId = s.UserId,
userName = u.Username
})//new anonymous object is possible in linq2entities
.ToList()
.Select(x => new HomeSongList(x.songId, x.userId, x.userName);
答案 1 :(得分:2)
您不能使用参数化构造函数,但可以使用初始值设定项,如果将select更改为以下值,它应该可以正常工作。
select new HomeSongList{SongId=s.SongId, UserId=s.UserId, Username=u.Username};
请注意,这将要求HomeSongList
具有无参数构造函数和可写属性。