【发布时间】:2010-09-16 22:38:48
【问题描述】:
我想知道是否有人可以帮助我。
我正在使用 VS2010、.Net 4、EF4,并且我正在尝试生成一个完全在代码中配置的对象上下文(仅代码,而不是模型优先或 db-first)。
简而言之,我愿意:
- 创建 ContextBuilder
- 为每个实体配置 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
如果我从配置中排除扇区,下一个实体也会发生同样的情况等等 - 所以要么所有实体/配置都是错误的,要么不是实体/配置问题
如果我在 Create() 调用之前检查 Builder,我可以看到 3 个与我的实体匹配的配置,并且指定的 id 字段具有以下内容:(我在 []s 中的 cmets)
Builder.Configurations.Items(0)[Sector].Items(0)[id].Value.StoreGeneratedPattern = Identity {1}
这似乎暗示配置被正确应用。
谁能解释我为什么会收到异常以及如何解决问题?
非常感谢
【问题讨论】:
标签: .net entity-framework ef4-code-only