我有一个包含2个字段的模型,这些字段具有到不同表的外键连接。他们有不同的名字,我无法弄清楚如何使关系发挥作用。
这是我的两个对象。 Visitor
和Home Teams
是我在建立之间关系时遇到的问题。
我得到的错误是:
“无法检索'Models.Game'的元数据 类型'Models.Game'上属性VisitorID的ForeignKeyAttribute不是 有效。在依赖项上找不到导航属性“团队” 输入'Models.Game'。名称值应该是有效的导航属性 名“。
public class Team
{
public Int64 TeamID { get; set; }
[Required(ErrorMessage = "{0} is required")]
[Display(Name = "Team Name")]
public string Name { get; set; }
[Required(ErrorMessage = "{0} is required")]
[Display(Name = "League Name")]
[ForeignKey("League")]
public Int64 LeagueID { get; set; }
public virtual League League { get; set; }
}
public class Game
{
public Int64 GameID { get; set; }
[Required(ErrorMessage = "{0} is required")]
[Display(Name = "Season Name")]
[ForeignKey("Season")]
public Int64 SeasonID { get; set; }
public virtual Season Season { get; set; }
[Required(ErrorMessage = "{0} is required")]
[DataType(DataType.DateTime)]
[Display(Name = "Game Time")]
public DateTime Time { get; set; }
[Required(ErrorMessage = "{0} is required")]
[Display(Name = "Visitor Team")]
[ForeignKey("Team")]
public Int64 VisitorID { get; set; }
public virtual Team Visitor { get; set; }
[Required(ErrorMessage = "{0} is required")]
[Display(Name = "Home Team")]
[ForeignKey("Team")]
public Int64 HomeID { get; set; }
public virtual Team Home { get; set; }
[Required(ErrorMessage = "{0} is required")]
[Display(Name = "Rink")]
[ForeignKey("Location")]
public Int64 LocationID { get; set; }
public virtual Location Location { get; set; }
public virtual List<GameEvent> GameEvents { get; set; }
}
答案 0 :(得分:0)
更改您的FK属性。它必须包含导航属性名称,而不是类型
[Required(ErrorMessage = "{0} is required")]
[Display(Name = "Visitor Team")]
[ForeignKey("Visitor")]
public Int64 VisitorID { get; set; }
答案 1 :(得分:0)
经过几天的研究,我发现我在游戏模型中做错了什么。马丁说我需要使用导航属性是正确的。我还需要将[ForeignKey]属性放在引用属性而不是ID上。我已经列出了以下针对访客和家庭团队的更正代码
[Required(ErrorMessage = "{0} is required")]
[Display(Name = "Visitor Team")]
public Int64 VisitorID { get; set; }
[ForeignKey("VisitorID")]
public virtual Team Visitor { get; set; }
[Required(ErrorMessage = "{0} is required")]
[Display(Name = "Home Team")]
public Int64 HomeID { get; set; }
[ForeignKey("HomeID")]
public virtual Team Home { get; set; }