C# 连接两个表以使用嵌套集合填充viewModel
我有两个表C# 连接两个表以使用嵌套集合填充viewModel,c#,entity-framework,linq,C#,Entity Framework,Linq,我有两个表客户和账户: 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 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; }
}
账户:
我编写了以下查询:
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
};
结果应该如下所示:
我的视图模型是SearchViewModel
:
public class SearchViewModel
{
public string Name { get; set; }
public IList<string> AccountNumber { get; set; }
}
如何使用linq
?任何帮助都将不胜感激 您正在寻找的是
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)
};
试试这个:
var result = db.Client.Select(client => new SearchViewModel
{
Name = client.Name,
AccountNumber = client.Account.Select(account => account.Name).ToList()
}).ToList();
伙计,你太棒了!在5分钟内接受你的答案!:)非常感谢你!
public class SearchViewModel
{
public string Name { get; set; }
public IList<string> AccountNumber { get; set; }
}
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" } },
};
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)
};
var result = db.Client.Select(client => new SearchViewModel
{
Name = client.Name,
AccountNumber = client.Account.Select(account => account.Name).ToList()
}).ToList();