我正在使用Code First Entity Framework方法,在我的OnModelCreating
函数中,我有以下代码:
With modelBuilder.Entity(Of FS_Item)()
.HasKey(Function(e) e.ItemKey)
.Property(Function(e) e.ItemRowVersion).IsConcurrencyToken()
.HasMany(Function(e) e.ItemInventories) _
.WithRequired(Function(e) e.Item).HasForeignKey(Function(e) e.ItemKey)
End With
在其他地方,我有一个Web API Get实现,其中包含一些诊断代码,我正在调试器中查看:
Public Function GetValue(ByVal id As String) As FS_Item
GetValue = If(data.FS_Item.Where(Function(i) i.ItemNumber = id).SingleOrDefault(), New FS_Item())
Dim c = GetValue.ItemInventories.Count
End Function
我希望c通过在FS_Inventory视图中查找ItemKey与检索到的FS_Item行的ItemKey匹配的行来获得非零值。但即使有匹配的行,我也会得到0。我是否正确地呼叫.HasMany
,.WithRequired
和.HasForeignKey
?
请注意.WithRequired
正在对前一行的返回值进行操作,而其他行则在With
块表达式上运行。
编辑已请求此FS_Item模型。这是:
Partial Public Class FS_Item
Public Property ItemNumber As String
Public Property ItemDescription As String
Public Property ItemUM As String
Public Property ItemRevision As String
Public Property MakeBuyCode As String
' Many many more properties
Public Property ItemRowVersion As Byte()
Public Property ItemKey As Integer
Private _ItemInventories As ICollection(Of FS_ItemInventory) = New HashSet(Of FS_ItemInventory)
Public Overridable Property ItemInventories As ICollection(Of FS_ItemInventory)
Get
Return _ItemInventories
End Get
Friend Set(value As ICollection(Of FS_ItemInventory))
_ItemInventories = value
End Set
End Property
End Class
编辑了解了一些有趣的内容。如果我将Dim c = GetValue.ItemInventories.Count
更改为:
Dim c = data.FS_ItemInventory.ToList()
Dim correctCount = GetValue.ItemInventories.Count
然后,correctCount获取值3.它就像它理解对象之间的关联,而不是如何自动查询它们,因为我习惯于从LINQ-to-SQL。 EF在这方面有何不同?
编辑我已确定可以使用此显式加载代码加载关联对象:
data.Entry(GetValue).Collection(Function(e) e.ItemInventories).Load()
我现在想要了解的是究竟是什么决定了一个实体是否会懒惰加载?从我能找到的所有迹象来看,它本应该懒散地加载。我甚至尝试将ItemInventories的声明更改为this,但是在尝试访问时我得到了NullReferenceException:
Public Overridable Property ItemInventories As ICollection(Of FS_ItemInventory)
答案 0 :(得分:0)
事实证明,我认为无关的代码已禁用延迟加载。我在FSDB的构造函数中有这个:
DirectCast(Me, IObjectContextAdapter).ObjectContext.ContextOptions.ProxyCreationEnabled = False
感谢EF 4 - Lazy Loading Without Proxies我看到这也会禁用延迟加载。添加代码的原因是由于另一个错误:
类型 'System.Data.Entity.DynamicProxies.FS_Item_64115A45C642902D6044AFA1AFD239E7DCB82FD000A10FE4F8DE6EA26A2AB418' 与数据合同名称 'FS_Item_64115A45C642902D6044AFA1AFD239E7DCB82FD000A10FE4F8DE6EA26A2AB418:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' 不是预期的。考虑使用DataContractResolver或添加任何 静态地知道已知类型列表的类型 - 例如, 通过使用KnownTypeAttribute属性或将它们添加到 传递给DataContractSerializer的已知类型列表。
根据Serialization of Entity Framework objects with One to Many Relationship,简单的解决方案是禁用代理。