.NET CTP5 Code First EF。将LazyLoading设置为False仍然不会导致一对一显式加载

时间:2012-08-21 10:33:18

标签: .net asp.net-mvc-3 code-first one-to-one entity-framework-5

我有以下(vb.net)模型类:

Public Class Contact
    Implements IModelEntity

    Public Property ID() As Integer

    Public Property Name() As String
    Public Overridable Property ContactDetails() As ContactDetails

    Public Sub New()
        ID = 0
        Name = ""
        ContactDetails = New ContactDetails
    End Sub
End Class

Public Class Person
    Inherits Contact
    Implements IModelEntity

    Public Property Surname() As String
    Public Property DOB() As DateTime

    Public Sub New()
        Surname = ""
        DOB = DateTime.Today
    End Sub
End Class

Public Class ContactDetails
    Implements IModelEntity

    Public Property ID() As Integer

    Public Property WebAddresses() As List(Of WebAddress)
    Public Property PhoneNumbers() As List(Of PhoneNumber)
    Public Property EmailAddresses() As List(Of String)
    Public Property SocialMediaAliases() As List(Of SocialMediaAlias)
    Public Property PostalAddresses() As List(Of PostalAddress)

    Public Sub New()
        ID = 0
        WebAddresses = New List(Of WebAddress)
        PhoneNumbers = New List(Of PhoneNumber)
        EmailAddresses = New List(Of String)
        SocialMediaAliases = New List(Of SocialMediaAlias)
        PostalAddresses = New List(Of PostalAddress)
    End Sub
End Class

Public Class eCRMContext
    Inherits DbContext

    Public Sub New()
        Me.Configuration.LazyLoadingEnabled = False
    End Sub

    Protected Overrides Sub OnModelCreating(modelBuilder As System.Data.Entity.DbModelBuilder)
        MyBase.OnModelCreating(modelBuilder)

        modelBuilder.Entity(Of Contact).HasRequired(Function(x) x.ContactDetails).WithOptional().WillCascadeOnDelete()
    End Sub

    Public Property ContactDetailsSet As DbSet(Of ContactDetails)
    Public Property Persons As DbSet(Of Person)
End Class

在人员控制器中,我有以下内容:

    ' GET: /Person/Edit/5

    Function Edit(id As Integer) As ViewResult
        Dim person As Person = db.Persons.Find(id)

        Return View(person)
    End Function

但是,即使将LazyLoading设置为False,也不会加载person.ContactDetails!我已检查数据库,并且已正确生成关系,并且首先生成的代码的键具有正确的值。发生了什么事?

更新

我也尝试过明确地做:

db.Persons.Where(Function(x) x.ID=id).Include("ContactDetails").SingleOrDefault()

以及

db.Persons.Where(Function(x) x.ID=id).Include(Function(y) y.ContactDetails).SingleOrDefault()

但它仍然无效。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

将延迟加载设置为false不会启用自动预先加载 - 它只是关闭延迟加载。如果您要加载关系,则必须在查询中使用Include方法(并且必须使用SingleOrDefault代替Find)。