简体   繁体   English

实体框架0对1关系-未设置对象引用

[英]Entity Framework 0 to 1 relationship - Object Reference Not Set

Having a bit of trouble having not long started with Entity Framework. 刚开始使用Entity Framework有点麻烦。

I have two tables which have a 0 to 1 relationship. 我有两个表具有0到1的关系。 When I select a row from the main table (staff) it's fine unless I select a row that has no joining record in the second table (status). 当我从主表(员工)中选择一行时,除非我选择第二个表(状态)中没有联接记录的行,否则可以。 If I do this, then it throws up 'Object reference not set to instance of an object' when it's trying to access the proprty of the second table: 如果执行此操作,则在尝试访问第二个表的属性时会引发“对象引用未设置为对象实例”:

        If Not cls.STATUS_DESC.STAFF_INFO Is DBNull.Value Then
            lblStatusDescription.Text = cls.STATUS_DESC.STAFF_INFO
        End If

The LINQ I use to get the record is: 我用来获取记录的LINQ是:

    Dim account As STAFF =
        (From a In sa.STAFFs
         Where a.STAFF_NO = staffno
         Select a).FirstOrDefault

There is no direct reference to the sub table in the statement, however the join is defined in the database diagram which allows me to reference the properties. 在语句中没有直接引用子表,但是联接是在数据库图中定义的,这使我可以引用属性。

I'm certain it's a very basic issue, but like I said I've only just started using it! 我敢肯定这是一个非常基本的问题,但是就像我说的那样,我才刚刚开始使用它!

I'm not sure if I can interpret your code correctly but I think it has to do with the Lazy Loading feature of Entity Framework. 我不确定是否可以正确解释您的代码,但我认为这与Entity Framework的延迟加载功能有关。 You must explicitly include the reference to load it into memory. 您必须明确包含引用才能将其加载到内存中。 You can to this by using the Include() method as below. 您可以使用Include()方法,如下所示。 I assume that STATUS_DESC is the name of the navigation property. 我假设STATUS_DESC是导航属性的名称。 Replace it with the actual one if I'm wrong: 如果我错了,请用实际的替换它:

Dim account As STAFF =
    (From a In sa.STAFFs Where a.STAFF_NO = staffno Select a) _
    .Include("STATUS_DESC") _
    .FirstOrDefault

Got around it by adding: 通过添加以下内容来解决它:

If Not cls.STATUS_DESC Is Nothing Then 如果不是cls.STATUS_DESC则为空

end if 万一

to the property call, which seems fairly obvious now I think about it. 到属性调用,现在我想起来似乎很明显。 Is this the most efficient way though, I would have thought that EF would have been able to handle a simple left join. 但是,这是最有效的方法吗?我以为EF可以处理简单的左联接。

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

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