我在ASP.NET Core WebAPI项目中使用Entity Framework Core 2.0.2。 我有以下实体:
NotificationReported.cs:
public class NotificationReported
{
public NotificationReported();
public int Id { get; set; }
public Guid Guid { get; set; }
public Guid PlantId { get; set; }
public ICollection<Photo> Photo { get; set; }
public ICollection<Response> Response { get; set; }
}
Photo.cs:
public class Photo
{
public Photo();
public int Id { get; set; }
public string Name { get; set; }
public string Status { get; set; }
public int NotificationReportedId { get; set; }
public NotificationReported NotificationReported { get; set; }
}
Response.cs:
public class Response
{
public Response();
public int Id { get; set; }
public int QuestionId { get; set; }
public int NotificationReportedId { get; set; }
public string Value { get; set; }
public NotificationReported NotificationReported { get; set; }
public Question Question { get; set; }
}
我想做LEFT JOIN,我想要包括那些孩子。这是我写的:
var tableNotifReported = _myNotifContext.NotificationReported
.Include(nr => nr.Response)
.ThenInclude(res => res.Question)
.ThenInclude(question => question.QuestionTypeRef)
.Include(nr => nr.Photo);
这是LINQ:
var query = (from notifReported in tableNotifReported
join response in _myNotifContext.Response
on notifReported.Id equals response.NotificationReportedId into joinResponse
from res in joinResponse.DefaultIfEmpty()
join question in _myNotifContext.Question
on res.QuestionId equals question.Id into joinQuestion
from ques in joinQuestion.DefaultIfEmpty()
join notifTemplate in _myNotifContext.NotificationTemplate
on notifReported.TemplateId equals notifTemplate.Guid
select new NotificationsReportedQuery
{
NotificationReported = notifReported,
Response = res,
Question = ques,
NotificationTemplate = notifTemplate
})
.Where(predicate)
.Select(nrq => nrq.NotificationReported)
.Distinct();
在调用ToListAsync()之后,我的对象列表没有他的孩子=&gt;响应(计数= 0)和照片(计数= 0)
但是当我使用通常的JOIN(内部加入)时,我的孩子就在这里。 缺少什么?
INNER JOIN的代码正在工作,但是我需要LEFT JOIN,因为在这种情况下NotificationReported可能没有用户回答的响应,因此INNER JOIN不会报告这种情况通知:
var query = (from notifReported in tableNotifReported
join response in _myNotifContext.Response
on notifReported.Id equals response.NotificationReportedId
join question in _myNotifContext.Question
on response.QuestionId equals question.Id
join notifTemplate in _myNotifContext.NotificationTemplate
on notifReported.TemplateId equals notifTemplate.Guid
select new NotificationsReportedQuery
{
NotificationReported = notifReported,
Response = response,
Question = question,
NotificationTemplate = notifTemplate
})
.Where(predicate)
.Select(nrq => nrq.NotificationReported)
.Distinct();