我想知道是否有人可以帮助我。
我正在使用 VS2010、.Net 4、EF4,并且正在尝试生成一个完全在代码中配置的对象上下文(仅代码,而不是模型优先或 db-first)。
简而言之,我这样做:
- 创建一个上下文构建器
- 为每个实体配置 ContextBuilder(指定 PK、FK、Nullable 等)
- 我要求 ContextBuilder 使用提供的连接字符串为我创建一个上下文。
上述最后一步失败,但有以下异常:
Unable to infer a key for entity type 'MyNamespace.MyEntityName'.
我认为这意味着它无法为我的实体推断主键/身份列。
我的代码如下。引用的ContextExtension
是一个包装类,它只是继承自ObjectContext
.
''Process starts with a call to this function
Private Shared Function GenerateContext() As ObjectContext
Dim ConnectionStringDetails = System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString")
Dim Builder = New ContextBuilder(Of ContextExtension)()
ConfigureDatabase(Builder)
'' Below line throws an exception:
'' Unable to infer a key for entity type 'MyNamespace.Sector'
Dim NewContext = Builder.Create(New SqlConnection(ConnectionStringDetails.ConnectionString))
Return DirectCast(NewContext, ObjectContext)
End Function
Private Shared Sub ConfigureDatabase(ByRef Builder As ContextBuilder(Of ContextExtension))
''Apply configurations for each of my 3 entities (see code blocks below for efinitions)
ConfigureEntity(Builder, New SectorConfig)
ConfigureEntity(Builder, New SolarSystemConfig)
ConfigureEntity(Builder, New UniverseConfig)
End Sub
Private Shared Sub ConfigureEntity(Of T)(ByRef Builder As ContextBuilder(Of ContextExtension), ByVal config As EntityConfiguration(Of T))
''simple pluralization of the entity set
ConfigureEntity(Builder, config, GetType(T).Name & "s")
End Sub
Private Shared Sub ConfigureEntity(Of T)(ByRef Builder As ContextBuilder(Of ContextExtension), ByVal config As EntityConfiguration(Of T), ByVal setName As String)
''add the configuration
Builder.Configurations.Add(config)
''register the set metadata
Builder.RegisterSet(Of T)(setName)
End Sub
我的实体定义如下:
Public Class Sector
Implements IEntity
Public Overridable Property id As Long Implements IEntity.id
Public Overridable Property Universe As Universe
Public Overridable Property SolarSystems As ICollection(Of SolarSystem)
End Class
我的实体配置是这样的:
Public Class SectorConfig
Inherits EntityConfiguration(Of Sector)
Public Sub New()
[Property](Function(x) x.id).IsIdentity()
Relationship(Function(x) x.Universe).FromProperty(Function(y) y.Sectors).IsRequired()
End Sub
End Class
如果我从配置中排除扇区,下一个实体也会发生同样的情况等等 - 所以要么所有实体/配置都是错误的,要么不是实体/配置问题
如果我Builder
在通话前检查Create()
,我可以看到与我的实体匹配的 3 个配置,并且id
指定的字段具有以下内容:(我在 []s 中的评论)
Builder.Configurations.Items(0)[Sector].Items(0)[id].Value.StoreGeneratedPattern = Identity {1}
这似乎意味着配置被正确应用。
有人可以解释为什么我会遇到异常以及如何解决问题吗?
非常感谢