简体   繁体   English

实体框架包含命令 - 左连接还是内连接?

[英]Entity framework Include command - Left or inner join?

As I was investigating the difference between Include and Join I found that : 在我调查IncludeJoin之间的区别时,我发现:

If the DB does not include a Foreign Keys -it has no navigation props so it's better to use Join 如果数据库包含外键 - 它没有导航道具,所以最好使用Join

If It does have a navigation props - then use Include . 如果它确实有导航道具 - 那么使用Include ( it also save a db hit.) (它还可以节省数据库命中率。)

But one answer here caught my attention: 这里的一个答案引起了我的注意:

Include is implemented as a join. Include实现为连接。 Depending on the nullability of the included link it is an inner or left join. 根据所包含链接的可为空性 ,它是内部左侧连接。

Question : 题 :

How does the nullity affects the left / inner join ? 无效如何影响左/内连接?

In Sql server I can have a Cities table and Persons table and a person can have a NULL CityID . 在Sql server中我可以有一个Cities表和Persons表,一个人可以有一个NULL CityID

Why does entity Framework decides for me what kind of join it is ? 为什么实体框架会为我决定它是什么类型的连接?

edit : visualization : 编辑:可视化:

在此输入图像描述

在此输入图像描述

Now lets change CityId to not null : 现在让我们将CityId更改为null:

在此输入图像描述

And here is the change : 这是改变:

在此输入图像描述

Suppose that in your class there is a [Required] constraint on City or CityID. 假设在您的课程中,City或CityID上有[Required]约束。 And suppose there are Person records without a (valid) City. 并且假设没有(有效)城市的人员记录。 The only way to satisfy the [Required] is to perform an inner join. 满足[Required]的唯一方法是执行内连接。

But as long as the constraints in your Db and model match (ie CityID INT NOT NULL ) it wouldn't really matter what kind of Join is used. 但是只要你的Db和模型中的约束匹配(即CityID INT NOT NULL ),使用何种类型的Join就不重要了。 That should be the normal case. 这应该是正常情况。

And without the constraint you would of course expect a Left Join. 没有约束,你当然会期望一个左连接。

I know this is an old question, but if anyone else lands here using EF Code First as I am, my issue was in the fluent mappings: 我知道这是一个老问题,但如果有人像我一样使用EF Code First登陆这里,我的问题在于流畅的映射:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Parent>()
            .HasOptional(a => a.Child) /* LEFT OUTER JOIN */
            .WithMany()
            .HasForeignKey(a => a.ChildId);
    }

is translated as a LEFT OUTER JOIN whereas 被翻译为LEFT OUTER JOIN

    modelBuilder.Entity<Parent>()
        .HasRequired(a => a.Child) /* INNER JOIN */
        .WithMany()
        .HasForeignKey(a => a.ChildId);

is translated as an INNER JOIN . 被翻译为INNER JOIN

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

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