我已阅读How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?,但我无法接听任何结果。它有以下错误:
类型上的属性'Footer_Item_Header_ID'上的ForeignKeyAttribute 'MyBlog.Tbl_Footer_Item'无效。导航属性 在依赖类型上找不到'Tbl_Footer_Header' 'MyBlog.Tbl_Footer_Item'。 Name值应该是有效的导航 财产名称。
在这一行:
Dim footerNavElements = db.Tbl_Footer_Headers.Where(Function(i) i.Footer_Header_Order = 1).Single.Items
这是我的父模型:
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
这是我的孩子模特:
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
我该怎么做才能使操作产生没有错误的结果?感谢。
答案 0 :(得分:5)
您的外键注释应该是属性的名称,而不是类型。
您的导航属性是标题:
Public Overridable Property Header As Tbl_Footer_Header
所以你的注释应该引用属性。将其更改为:
<ForeignKey("Header")>
Public Property Footer_Item_Header_ID() As Integer