如何在C#中使用LINQ返回带有列表的类?

时间:2016-10-13 18:49:51

标签: linq

我有一个“个人资料”和“地址”表个人资料表包含一个人的记录,而地址表包含其多个地址。

我想编写LINQ查询以在一个Query中返回单个人记录及其多个地址。所以我用“profileId”,“firstName”和地址列表创建了一个自定义类。

我需要这样的输出请帮助。

1(profileId)

标记(firstName)

------ Sanday(地址一)

------ Stronsay(地址二)

------ Foula(地址三)

public class profileDetails
    {
        public int profileIdData { get; set; }
        public string firstNameData { get; set; }
        public List<lstAddress> lstAddressData { get; set; }
    }
   public class lstAddress
    {
        public int addressId { get; set; }
        public string address { get; set; }
    }

    //This is my query
     var result = (from profile in DbContext.Profiles
                      join address in DbContext.Addresses
                      on profile.profileId equals address.addressId
                      select new profileDetails()
                      {
                          profileIdData = profile.profileId,
                          firstNameData = profile.firstName,
                          lstAddressData = new { address.addressId, address.address }.toList()
                      }
                     )

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用Include方法?像这样:

var result = (from profile in DbContext.Profiles
              join address in DbContext.Addresses
              on profile.profileId equals address.addressId).Include("lstAddressData");

lstAddressData 名称在上面的示例中可能不正确,它引用了要用地址项填充的引用属性)