简体   繁体   中英

C# Entity Framework join tables

I am trying to get the same results as with a SQL query using Entity Framework method syntax.

在此处输入图片说明

SQL query :

select 
    mr.*, mrf.userId as RequesterUserId, mrt.UserId as ReceiverUserId 
from 
    MoneyRequests mr
inner join  
    MoneyReqFrom mrf on mr.MoneyRequestId = mrf.MoneyRequestId
inner join  
    MoneyReqTo mrt on mr.MoneyRequestId = mrt.MoneyRequestId
where 
    mr.MoneyRequestId = 'acfc8008-4cf7-47ec-a3fe-0fe245af77cc'

EF Linq method syntax :

var moneyreqResponse = context.MoneyRequests
                              .Join(context.MoneyReqFroms, 
                                      mr => mr.MoneyRequestId, 
                                      mrf => mrf.MoneyRequestId, 
                                      (mr, mrf) => new 
                                                   { 
                                                       MoneyRequestId = mr.MoneyRequestId,
                                                       Amount = mr.Amount,
                                                       RequestType = mr.RequestType,
                                                       CreationDate = mr.CreationDate,
                                                       RequesterUserId = mrf.UserId 
                                                    }) 
                              .Join(context.MoneyReqTos, 
                                       mr => mr.MoneyRequestId, 
                                       mrt => mrt.MoneyRequestId,
                                       (mr, mrt) => new 
                                                    { 
                                                        MoneyRequestId = mr.MoneyRequestId,
                                                        Amount = mr.Amount, 
                                                        RequestType = mr.RequestType,
                                                        CreationDate = mr.CreationDate,
                                                        ReceiverUserId = mrt.UserId, 
                                                        Email = mrt.Email 
                                                    }) 
                              .Where(fullEntry => fullEntry.MoneyRequestId == "acfc8008-4cf7-47ec-a3fe-0fe245af77cc") 
                              .ToList();

I retrieve the data from the database except the column RequesterUserId .

Do you know why?

Thanks

Your query returns a MoneyRequests type, which I belive does not contain RequesterUserId .

You should define a new type with all the properties you need (those returned by the join) and add it to your DbContext.

Also probably you want to mark your new type as keyless

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM