如何使用DTO和linq压缩webapi EF

时间:2016-08-10 12:42:40

标签: entity-framework linq asp.net-web-api

我正在尝试使用DTO和linq来平整我的webapi EF,但不太确定如何做到这一点。我的最终目标是,我想返回USERNAME = x的所有四个帐户。

在此示例中,有1个用户名可访问1个客户端,而该1个客户端有4个帐户。

如何使结果返回4个条目,每个帐户1个?

这是我到目前为止所拥有的......

            var x2 = from b in db.AspNetUsers
                 where b.UserName == username
                 select new AspNetUserDetailDTO()
                 {
                     UserName = b.UserName,
                     Email = b.Email,
                     Mapping_UserClient = b.Mapping_UserClient
                     //ClientName = b.Mapping_UserClient.SelectMany<Mapping_UserClient>(x => x.ClientID)
                     //Mapping_UserClient = b.Mapping_UserClient
                 };

下面是我的sql图。

sql diagram

所以我尝试编写一个简单的SQL查询来返回我正在寻找的基本结果...现在我不知道如何在LINQ中执行此操作

SELECT 
dbo.Clients.ClientName
,dbo.Mapping_UserClient.ClientID
,*
 FROM [xxx].[dbo].[AspNetUsers]
 inner join dbo.Mapping_UserClient on     dbo.Mapping_UserClient.AspNetUsersID    = dbo.AspNetUsers.Id
 inner join dbo.Clients on dbo.Clients.ClientID =   dbo.Mapping_UserClient.ClientID
 inner join dbo.Mapping_ClientAccount on dbo.Mapping_ClientAccount.ClientID    = dbo.Clients.ClientID
 inner join dbo.Accounts on dbo.Accounts.AccountID =   dbo.Mapping_ClientAccount.AccountID

其中Email =&#39; dddd&#39;

1 个答案:

答案 0 :(得分:2)

翻译上面的查询,你会在Linq中得到类似的东西:

var query = (from acc in db.Accounts
             join mca in db.Mapping_ClientAccount
                on acc.AccountId equals mca.ClientID
             join cli in db.Clients
                on mca.ClientID equals cli.ClientID
             join muc in db.Mapping_UserClient
                on cli.ClientID equals muc.ClientID
             join anu in db.AspNetUsers
                on muc.AspNetUsersID equals anu.Id
            where anu.UserName == username
            select new AspNetUserDetailsDTO()
            {
                ClientName = cli.ClientName,
                ClientID = cli.ClientID
            }).ToList();