连接两个表以使用嵌套集合填充viewModel

时间:2016-08-25 12:20:15

标签: c# entity-framework linq

我有两张表ClientAccount

public partial class Client
{
    public Client()
    {
        this.Account = new HashSet<Account>();
        this.Doc = new HashSet<Doc>();
    }

    public int ClientId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Account> Account { get; set; }
    public virtual ICollection<Doc> Doc { get; set; }
}

public partial class Account
{
    public Account()
    {
        this.Doc = new HashSet<Doc>();
    }

    public int AccountId { get; set; }
    public string Name { get; set; }
    public int Fk_ClientId { get; set; }

    public virtual Client Client { get; set; }
    public virtual ICollection<Doc> Doc { get; set; }
}

数据如下所示:

客户端:

ClientID     Name
   1         Ben
   2         Joseph

帐户:

AccountID     Name             Fk_ClientId
   1         BenAccount1           1
   2         BenAccount2           1
   3         JosephAccount1        2
   4         JosephAccount2        2
   5         JosephAccount3        2

我写了以下查询:

var query = from clnt in db.Client
                        join acnt in db.Account 
                             on clnt.ClientId equals acnt.Fk_ClientId
                        select new SearchViewModel
                        {
                            Name = clnt.Name,
                            AccountNumber = //don't know what I should write here
                        };

结果应如下所示: enter image description here

我的viewModel是SearchViewModel

public class SearchViewModel
{
    public string Name { get; set; }
    public IList<string> AccountNumber { get; set; }        
}

如果我手动创建SearchViewModel实例,我可以模仿结果:

List<SearchViewModel> searchVM = new List<SearchViewModel>()
{ 
   new SearchViewModel(){Name="Ben", AccountNumber = new List<string>() { "BenAccount1", 
           "BenAccount2" } }, 
   new SearchViewModel(){Name="Joseph", AccountNumber = new List<string>() {  
           "JosephAccount1", "JosephAccount2", "JosephAccount3" } },                    
};

如何使用linq制作此类结果? 任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

您正在寻找的是Groupjoin方法。 在查询语法中,它看起来像这样:

var query = from clnt in db.Client
            join acnt in db.Account on clnt.ClientId equals acnt.Fk_ClientId into accounts
            select new SearchViewModel
            {
                Name = clnt.Name,
                AccountNumber = accounts.Select(account => account.Name)
            };

答案 1 :(得分:1)

试试这个:

var result = db.Client.Select(client => new SearchViewModel
{
    Name = client.Name,
    AccountNumber = client.Account.Select(account => account.Name).ToList()
}).ToList();
相关问题