迁移期间未找到Entity Framework外键

在将密钥和外键添加到数据模型后设置迁移时遇到意外错误。 我正在使用带有.NET framework 4.5的VS2013 Express。

在为Entity Framework创建数据模型时,由于类之间的关系键不符合惯例,我使用MS Data Developer Center中概述的数据注释。 这是类代码:

using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BacklogTracker.Models { public class WorkOrder { [Key] public string woNum { get; set; } public string woClosingStatus { get; set; } [ForeignKey("ID")] public virtual ICollection woNotes { get; set; } [ForeignKey("machSN")] public virtual Machine woMachine { get; set; } [ForeignKey("ID")] public virtual ICollection woSegments { get; set; } } public class Machine { [Key] public string machSN { get; set; } public string machLocation { get; set; } public string machModel { get; set; } } public class Segment { [Key] public int ID { get; set; } public uint segNum { get; set; } public string segRepair { get; set; } [ForeignKey("ID")] public virtual ICollection segNotes { get; set; } } public class Note { [Key] public int ID { get; set; } public DateTime notetimestamp { get; set; } public string notestring { get; set; } } } 

但是,当我尝试通过在程序包管理器控制台中执行enable-migrations更新模型后执行enable-migrations时,出现以下错误:

类型为“BacklogTracker.Models.WorkOrder”的属性“woMachine”上的ForeignKeyAttribute无效。 在依赖类型“BacklogTracker.Models.WorkOrder”上找不到外键名称“machSN”。 Name值应该是以逗号分隔的外键属性名称列表。

为什么我的foreign key name 'machSN'找不到?

我认为你的模型中有一些错误。 ForeignKey关系的默认代码第一约定期望在dependend end( WorkOrder )中声明与主端( Machine )的主键属性匹配的外键属性。 它们没有必要具有相同的名称,请查看此链接 。 因此,在WorkOrder类中声明名为machSN的属性:

 public class WorkOrder { [Key] public string woNum { get; set; } public string woClosingStatus { get; set; } public virtual ICollection woNotes { get; set; } public string machSN { get; set; } [ForeignKey("machSN")] public virtual Machine woMachine { get; set; } public virtual ICollection woSegments { get; set; } } 

您可以在woNoteswoSegments导航属性中找到其他错误。 在一对多关系的这一方,你没有声明FK,在另一方面,在NoteSegment类中,例如:

 public class Note { [Key] public int ID { get; set; } public DateTime notetimestamp { get; set; } public string notestring { get; set; } [ForeignKey("Order)] public string woNum { get; set; } public virtual WorkOrder Order{get;set;} } 

Segment类中也删除了由segNotes导航属性上的ForeignKey属性,原因与前面解释的相同。

 public class Segment { [Key] public int ID { get; set; } public uint segNum { get; set; } public string segRepair { get; set; } public virtual ICollection segNotes { get; set; } }