我想知道是否有人可以帮助我。
我正在使用VS2010,.Net 4,EF4,我正在尝试生成一个完全在代码中配置的objectcontext(仅代码,而不是model-first或db-first)。
简而言之,我这样做:
上一步失败,但有以下异常:
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
字段具有以下内容:(我在[]中的注释)
Builder.Configurations.Items(0)[Sector].Items(0)[id].Value.StoreGeneratedPattern = Identity {1}
这似乎意味着正确应用了配置。
有人可以解释为什么我得到例外以及如何解决问题?
非常感谢
答案 0 :(得分:0)
我可以使用以下语法解决此问题:
Public Class SectorConfig
Inherits EntityConfiguration(Of Sector)
Public Sub New()
HasKey(Function(x) X.id)
[Property](Function(x) x.id).IsIdentity()
Relationship(Function(x) x.Universe).FromProperty(Function(y) y.Sectors).IsRequired()
End Sub
End Class
请注意额外的HasKey()调用