在新对象中选择可选的导航属性

时间:2015-10-16 18:33:31

标签: vb.net entity-framework linq linq-to-entities

我有一组业务对象,我正在尝试使用Entity Framework查询填充这些对象。 MS-SQL数据库和EF模型都反映了以下类。

请注意ParentTypeChildType的“0..1到很多”相关。

问题是我想加载ParentType对象作为ChildType对象的属性,但是如上所述,如果ParentType为空,我得{{1}因为InvalidOperationException中的具体化值是空的。

另请注意,我不想将ParentType数据展平为ParentType中的可空字段,因为稍后我想按整个ChildType对象对结果列表进行分组。

ParentType

编辑:试图澄清,我正在寻找的是我可以Public Class ParentType Public Property ParentTypeID as Integer Public Property Description as String End Class Public Class ChildType Public Property ChildTypeID As Integer Public Property ParentTypeID As Integer? Public Property Description As String Public Property ParentType As ParentType Public Shared Function GetChildTypes() As IQueryable(Of ChildType) Dim db As New DataAccess.MyModelEntities() Return ( From c In db.ChildTypes Select New ChildType With { .ChildTypeID = c.ChildTypeTypeID, .ParentTypeID = c.ParentTypeID, .Description = c.Description, .ParentType = New ParentType With { .ParentTypeID = c.ParentType.ParentTypeID, .Description = c.ParentType.Description } } ) End Function End Class 编写的方式,但仅当c.ParentType不为空时。

2 个答案:

答案 0 :(得分:0)

哦,伙计 - 我过去一直在努力解决这个问题。

在实体框架中,基本上它将导航属性保存为外键。这意味着当您加载具有导航属性的实体时,它不会加载该属性类型的实体的属性,因为它具有的是外键。

如果要加载相关实体的属性,则必须使用say Eager Loading(使用Gert Arnold示例)在查询中包含该属性,或者在过程中查询其他表本身。

在你的特定情况下,我猜你会使用这样的东西:

LocalDateTime

或Gert推荐的Eager Loading方式:

From c In db.ChildTypes
            Select New ChildType With {
                .ChildTypeID = c.ChildTypeTypeID,
                .ParentTypeID = c.ParentTypeID,
                .Description = c.Description,
                .ParentType = New ParentType With {
                    .ParentTypeID = c.ParentTypeID,
                    .Description = (From parent In db.ParentTypes Select parent.Description Where parent.ParentTypeID = c.ParentTypeID).FirstOrDefault()
                }

答案 1 :(得分:0)

最后,我想我必须允许创建ParentType对象并允许其所有成员都可以为空。对我来说,这不是理想的解决方案,但它使查询工作正常。

Public Class ParentType
    Public Property ParentTypeID as Integer?
    Public Property Description as String
End Class

我可以检查ParentType Is Nothing

,而不是检查ParentType.ParentTypeID.HasValue