EF Code First First外键推断的问题

时间:2011-01-17 03:04:17

标签: entity-framework code-first

我第一次使用EF Code First,而我无法推断出我的类型之间的关系。鉴于这两种类型:

<Table("grpGroupType")>
Public Class GroupType
  <Key()>
  Public Property GroupTypeID As Integer

  <Required()>
  Public Property IsActive As Boolean

  <Required()>
  <MaxLength(100)>
  Public Property Description As String

  Public Overridable Property GroupDefinitions() As ICollection(Of GroupDefinition)
End Class

<Table("grpGroupDefinition")>
Public Class GroupDefinition
  <Key()>
  Public Property GroupDefinitionID As Integer

  <Required()>
  Public Property GroupTypeID As Integer

  <Required()>
  Public Property IsActive As Boolean

  <Required()>
  Public Property ScopeValue As Integer?

  <Required()>
  <MaxLength(100)>
  Public Property Description As String

  Public Overridable Property GroupType As GroupType
End Class

我可以使用DbContext类加载和保存数据,但是当我尝试访问GroupType.GroupDefinitions或GroupDefinition.GroupType时,它们都返回Nothing。我的DbContext类在这里:

Public Class PD
  Inherits DbContext

  Public Property GroupDefinitions As DbSet(Of GroupDefinition)
  Public Property GroupTypes As DbSet(Of GroupType)

  Protected Overrides Sub OnModelCreating(ByVal modelBuilder As     ModelConfiguration.ModelBuilder)
    modelBuilder.Entity(Of GroupDefinition)().HasKey(Function(b) b.GroupDefinitionID)
    modelBuilder.Entity(Of GroupType)().HasKey(Function(b) b.GroupTypeID)
  End Sub
End Class

似乎没有太多关于密钥推断的文档,但我确实找到了这个blog post,看来我的类遵循自动推理的规则。

有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:0)

尝试添加

Public Property GroupTypeID As Integer

到你的GroupDefinition类。

即使它不需要,并且在早期版本中不需要,但似乎CTP5版本的EF需要更明确的定义,以便它可以获取关系。我个人希望他们在RTM之前解决这个问题。

答案 1 :(得分:0)

我明白了。我有一个在本地创建DbContext的SelectOne方法。我在调用代码中创建了上下文并将其传递给SelectOne,现在一切正常。谢谢大家。