开发者

Problem with EF Code First foreign key inference

I'm working with EF Code First for the first time, and I'm having trouble getting it to infer the relationships between my types. Given these two types:

<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

and

<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

I can load and save data using the DbContext class, but when I try to access GroupType.GroupDefinitions or GroupDefinition.GroupType, they both return Nothing. My DbContext class is here:

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

There doesn't seem to be much documentation on key inference, but I did find this blog post and it appears that my classes follow the rules for automatic inference.

Could开发者_如何学编程 anyone point me in the right direction?


Try adding

Public Property GroupTypeID As Integer

To your GroupDefinition class.

Even though it shouldn't be needed, and was not needed in earlier versions, it appears that the CTP5 version of EF needs a little more explicit definition so it can pick up relationships. Personally I hope they fix this before RTM.


I figured it out. I had a SelectOne method that was creating the DbContext locally. I created the context in the calling code and passed it to SelectOne, and all works now. Thanks everyone.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜