简体   繁体   English

实体框架-使用.include()和.Select()进行“紧急加载”-如何使用左联接而不是内联接?

[英]Entity Framework - “eager loading” using .Include() and .Select() - how to use a LEFT JOIN rather than INNER JOIN?

Here is a query I'm working on in Entity Framework 5.0.0 RC (code first) with .NET 4.0 这是我正在使用.NET 4.0在Entity Framework 5.0.0 RC(代码优先)中进行的查询

I'm new to Entity Framework, so I'm still getting my head around how to structure the queries, particularly around selecting "child" related data. 我是Entity Framework的新手,所以我仍然在设法构造查询方面,尤其是在选择与“子”相关的数据方面。

I'm using "eager loading" so I get all of the related data at once. 我正在使用“紧急加载”,因此我可以一次获取所有相关数据。 But I'm having a problem in that not all of the Drops are being retrieved. 但是我有一个问题,因为并不是所有的Drops都可以被检索到。

var loads = context.Loads
            .Include(
                p => p.Device
            )
            .Include(
                p => p.Drops.Select(
                    a => a.Customer
                )
            ).Include(
                q => q.Drops.Select(
                   b => b.Items.Select(
                       c => c.Product
                   )
                )
            ).Where(
                u => u.Id.Equals(id)
            );

The problem is that in the generated SQL query, the Customers are being INNER JOINED to the Drops, thus excluding Drops which don't have a Customer. 问题在于,在生成的SQL查询中,客户被内联到Drops中,因此排除了没有Customer的Drops。

So how do I make it do a LEFT JOIN between those two entities? 那么,如何在这两个实体之间进行LEFT JOIN?

.Include appears to do left joins - so why not .Select ? .include似乎做左连接-那么为什么不选择。

Is there a method other than .Select that I can use which will do a LEFT JOIN ? 除了.Select之外,还有其他方法可以使用LEFT JOIN吗?


UPDATE 更新

After chatting with Amiram I realised that I had set my Drop model up incorrectly. 与Amiram聊天之后,我意识到我没有正确设置Drop模型。 I needed to set the CustomerID column to be optional: 我需要将CustomerID列设置为可选:

public class Drop
{
    public int Id { get; set; }
    public int? CustomerId { get; set; }
    public int LoadId { get; set; }
    public DateTime Date { get; set; }

    public virtual Customer Customer { get; set; }
    public virtual ICollection<DropItem> Items { get; set; }
}

I should have immediately thought of this, but to be honest I was put off by the fact that .Include() always does a LEFT JOIN, regardless of the cardinality in the relationship of the models. 我应该立即想到这一点,但老实说,不管模型之间的基数如何,.include()总是会进行左联接,这一事实使我感到不满意。 I was thinking .Select() must have some similar behaviour, but no it was just obeying how the model was configured :) 我在想.Select()必须具有类似的行为,但是不,它只是服从于模型的配置方式:)

由于Drop.CustomerID的类型为int而不是可为null的int(在聊天中查找),因此drop与客户内部连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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