我在将键和外键添加到我的数据模型后设置迁移时遇到意外错误。我正在使用带有 .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<Note> woNotes { get; set; }
[ForeignKey("machSN")]
public virtual Machine woMachine { get; set; }
[ForeignKey("ID")]
public virtual ICollection<Segment> 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<Note> segNotes { get; set; }
}
public class Note
{
[Key]
public int ID { get; set; }
public DateTime notetimestamp { get; set; }
public string notestring { get; set; }
}
}
但是,当我尝试通过在包管理器控制台中执行 enable-migrations
更新模型后执行迁移时,出现以下错误:
The ForeignKeyAttribute on property 'woMachine' on type 'BacklogTracker.Models.WorkOrder' is not valid. The foreign key name 'machSN' was not found on the dependent type 'BacklogTracker.Models.WorkOrder'. The Name value should be a comma separated list of foreign key property names.
为什么找不到我的外键名称“machSN”
?
最佳答案
我认为您的模型有一些错误。 ForeignKey
关系的默认代码优先约定应在从属端 (WorkOrder
) 中声明与主体端 () 的主键属性匹配的外键属性机器
)。他们不必具有相同的名称,检查此 link .因此,在您的 WorkOrder
类中声明一个名为 machSN
的属性:
public class WorkOrder
{
[Key]
public string woNum { get; set; }
public string woClosingStatus { get; set; }
public virtual ICollection<Note> woNotes { get; set; }
public string machSN { get; set; }
[ForeignKey("machSN")]
public virtual Machine woMachine { get; set; }
public virtual ICollection<Segment> woSegments { get; set; }
}
您可以在 woNotes
和 woSegments
导航属性中找到其他错误。在一对多关系的这一边,你没有声明 FK,在另一边,在 Note
和 Segment
类中,例如:
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<Note> segNotes { get; set; }
}
关于c# - 迁移期间未找到 Entity Framework 外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28481781/