可能的重复项:
LINQ to SQL:返回匿名类型?
在 linq 联接上,我应该对 List<> 使用什么返回类型? 我正在连接下面的多个表,我收到错误'Cannot implicitly convert type System.Collections.Generic.List<AnonymousType#1> to System.Collections.Generic.List<CargoTanksDAL.aspnet_Users>
public List<> GetAspnetUsersWithMembershipAndCompany()
{
using (DevCargoEntities db = new DevCargoEntities())
{
var users = from u in db.aspnet_Users
join mem in db.aspnet_Membership on u.UserId equals mem.UserId
join cl in db.CT_CompanyLogIn on u.UserName equals cl.UserLogIn
join companies in db.CT_Companies on cl.CompanyID equals companies.CompanyID
select new
{
u.UserId,
u.UserName,
mem.Email,
mem.IsLockedOut,
mem.IsApproved,
mem.CreateDate,
companies.CompanyName
};
return users.ToList();
}
}
None。联接在这里无关紧要,选择无关紧要,并且您选择匿名类型。不能返回匿名类型。最好创建一个包含要返回的属性的新类,并实例化该类型。
理论上你可以返回动态或对象,但这是一条你真的不想走的路。相信我。
我会为这个用户创建一个新类..
public class SomeKindOfUser
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public bool IsLockedOut { get; set; }
public bool IsApproved { get; set; }
public DateTime CreateDate { get; set; }
public string CompanyName { get; set; }
}
现在您可以使用
public List<SomeKindOfUser> GetAspnetUsersWithMembershipAndCompany()
然后在选择:
select new SomeKindOfUser
{
UserId = u.UserId,
UserName = u.UserName,
Email = mem.Email,
IsLockedOut = mem.IsLockedOut,
IsApproved = mem.IsApproved,
CreateDate = mem.CreateDate,
CompanyName = companies.CompanyName
};