linq join返回类型

时间:2013-01-22 18:29:15

标签: c# linq

  

可能重复:
  LINQ to SQL: Return anonymous type?

我对List&lt;&gt;使用什么返回类型?在linq加入?我正在加入下面的多个表格,我收到错误'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();
        }
    }

2 个答案:

答案 0 :(得分:4)

无。此处的连接无关紧要,选择确实如此,您选择匿名类型。您无法返回匿名类型。最好创建一个包含要返回的属性的新类,并实例化该类型。

理论上你可以返回动态或对象,但这是你真正不想走的路径。相信我。

答案 1 :(得分:1)

我会为这个用户创建一个新类..

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
                        };