EF Include始终为第一个导航属性产生INNER JOIN [英] EF Include always produces INNER JOIN for the first Navigation Property

查看:126
本文介绍了EF Include始终为第一个导航属性产生INNER JOIN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用代码优先"方法,并具有以下模型:

I'm using the Code First approach and have the following Model:

public class Person
{
    public int ID {get; set;}
    public string Name {get; set;}

    public int CurrentStationID {get; set;}
    public virtual Station CurrentStation {get; set;}

    public int CurrentTransportationID {get; set;}
    public virtual Transportation CurrentTransporation {get; set;}
}

以及我的控制器中的以下代码:

And the following code in my controller:

Models.Person model = myDBContext.Persons
                        .Include("CurrentStation")
                        .Include("CurrentTransportation")
                        .Where(p => p.ID == 1)
                        .FirstOrDefault();

即使数据库表人员"中存在带有(1,"Testname",0,0)的行,

模型"也将为NULL.

"model" is going to be NULL even though a row with (1, "Testname", 0, 0) exists in the DB table "persons".

上面的代码使用[...] INNER JOIN stations AS [...] LEFT JOIN transportations [...]生成了一个SQL语句.对于我的所有模型,它始终对第一个导航属性执行INNER JOIN,无论基础表/类型是什么,或我按什么顺序指定它们,始终都是第一个Include().

The above generates a SQL-statement with [...] INNER JOIN stations AS [...] LEFT JOIN transportations [...]. It always does an INNER JOIN for the first navigational property, for all my models, regardless what the underlying table/type is or in which order I specify them, it's always the first Include().

我确实想要一个INNER JOIN而是一个LEFT JOIN,因为数据库中不需要"CurrentStation".

I do not want an INNER JOIN but a LEFT JOIN on all of them, since "CurrentStation" is not required to be in the database.

EF为什么要这样做???我不明白,但我想了解.我尚未在任何属性上指定[Required]属性,但其行为与我一样.

Why does EF do this??? I don't understand but I want to understand. I have not specified a [Required]-attribute on any of the properties, yet it behaves as if I did.

不幸的是,没有[Optional]属性,通过OnModelCreate-override进行"HasOptional()"不是我的选择.

Unfortunately there's no [Optional]-attribute and doing a "HasOptional()" via the OnModelCreate-override is not an option for me.

推荐答案

如果我没记错的话,为了允许属性是可选的,或者在数据库意义上允许为空,则必须使该属性为空.因此,对于CurrentStationId属性,您可以尝试如下声明:

If I am not mistaken, in order to allow a property to be optional or in the database sense, nullable, you must make the property nullable. So in the case of your CurrentStationId property you can try declaring it as follows:

 public int? CurrentStationId {get;set;}

更新 这篇帖子可能对您的情况有所帮助

UPDATE This post may be of some help for your situation.

这篇关于EF Include始终为第一个导航属性产生INNER JOIN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆