我写了这个linq查询,
var userProfile = (from u in ent.UserProfile
join ud in ent.tblUserDetails on u.UserId equals ud.UserId
join uc in ent.tblUserContacts on u.UserId equals uc.UserId
select new
{
u.UserId,
u.UserName,
u.NameSurname,
ud.CityID,
ud.EducationStatusID,
ud.Birthday,
ud.About,
ud.ProfilePicture,
ud.PrestigePoint,
uc.FacebookAccount,
uc.TwitterAccount,
uc.GooglePlusAccount,
uc.LinkedInAccount,
uc.Website
}).ToList();
return userProfile;
我也设计了模型类,
public class UserProfileGeneral
{
public Nullable<int> UserId { get; set; }
public string About { get; set; }
public Nullable<DateTime> Birthday { get; set; }
public Nullable<byte> CityID { get; set; }
public Nullable<byte> EducationStatusID { get; set; }
public Nullable<byte> PrestigePoint { get; set; }
public string ProfilePicture { get; set; }
public string UserName { get; set; }
public string NameSurname { get; set; }
public string FacebookAccount { get; set; }
public string GooglePlusAccount { get; set; }
public string LinkedInAccount { get; set; }
public string TwitterAccount { get; set; }
public string Website { get; set; }
}
但Visual Studio会抛出此错误:
无法隐式转换类型&#39; System.Collections.Generic.List&#39;到&#39; System.Collections.Generic.List&#39;
我该如何解决这个问题?
感谢。
答案 0 :(得分:1)
您目前正在投射到匿名类型,而不是UserProfileGeneral
的实例。
而不是
select new {
你想做
select new UserProfileGeneral()
var userProfile = (from u in ent.UserProfile
join ud in ent.tblUserDetails on u.UserId equals ud.UserId
join uc in ent.tblUserContacts on u.UserId equals uc.UserId
select new UserProfileGeneral()
{
UserId = u.UserId,
UserName = u.UserName,
NameSurname = u.NameSurname,
CityID = ud.CityID,
//and so on
}).ToList();
答案 1 :(得分:0)
您将返回匿名类型的列表,而不是您的实际类型。
将Select Select块替换为:
Select New UserProfileGeneral {
UserId = u.UserId,
UserName = u.UserName,
// etc...
}
您还可以在UserProfile
类上声明一个构造函数,该构造函数将采用实例类型的三个参数,并负责在内部设置属性。