The ForeignKeyAttribute on property is not valid

asp.net-mvc asp.net-mvc-3 entity-framework vb.net

Question

I've read How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3? but I can't get my call to yield any results. It has the following error:

The ForeignKeyAttribute on property 'Footer_Item_Header_ID' on type 'MyBlog.Tbl_Footer_Item' is not valid. The navigation property 'Tbl_Footer_Header' was not found on the dependent type 'MyBlog.Tbl_Footer_Item'. The Name value should be a valid navigation property name.

On this line:

Dim footerNavElements = db.Tbl_Footer_Headers.Where(Function(i) i.Footer_Header_Order = 1).Single.Items

Here is my parent model:

Imports System.Data.Entity
Imports System.ComponentModel.DataAnnotations

Public Class Tbl_Footer_Header

    <Key()> Public Property Footer_Header_ID() As Integer
    Public Property Footer_Header_Content() As String
    Public Property Footer_Header_Order() As Integer

    Public Overridable Property Items As ICollection(Of Tbl_Footer_Item)

End Class

Public Class FooterHeaderDbContext
    Inherits DbContext

    Public Property Tbl_Footer_Headers As DbSet(Of Tbl_Footer_Header)

End Class

Here is my child model:

Imports System.Data.Entity
Imports System.ComponentModel.DataAnnotations

Public Class Tbl_Footer_Item

    <Key()> Public Property Footer_Item_ID() As Integer
    <ForeignKey("Tbl_Footer_Header")>
    Public Property Footer_Item_Header_ID() As Integer
    Public Property Footer_Item_Content() As String
    Public Property Footer_Item_Link() As String
    Public Property Footer_Header_Order() As Integer

    Public Overridable Property Header As Tbl_Footer_Header

End Class

Public Class FooterItemDbContext
    Inherits DbContext

    Public Property Tbl_Footer_Items As DbSet(Of Tbl_Footer_Item)
    Public Property Tbl_Footer_Headers As DbSet(Of Tbl_Footer_Header)

End Class

What can I do to make the action yield a result without error? Thanks.

1
1
5/23/2017 12:04:00 PM

Accepted Answer

Your foreign key is annotation should be for the name of the property, not the type.

Your navigation property is Header:

Public Overridable Property Header As Tbl_Footer_Header

So your annotation, should reference the property. Change it to:

<ForeignKey("Header")>
Public Property Footer_Item_Header_ID() As Integer
5
9/4/2012 4:14:01 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow