在将键和外键添加到数据模型后设置迁移时,我遇到意外错误。我使用的是 VS2013 Express,带有 .NET Framework 4.5。
为实体框架创建数据模型时,由于类之间的关系键不是惯例所期望的,因此我使用数据注释,如微软数据开发中心 https://msdn.microsoft.com/en-us/data/jj591583#Relationships。这是类代码:
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
在包管理器控制台中,我收到以下错误:
类型上属性“woMachine”的ForeignKeyAttribute
“BacklogTracker.Models.WorkOrder”无效。外键名称
在依赖类型上找不到“machSN”
'BacklogTracker.Models.WorkOrder'。名称值应该是逗号
外键属性名称的分隔列表。
为什么是我的foreign key name 'machSN'
没有被发现?
我认为你的模型有一些错误。默认代码优先约定ForeignKey
关系预计已在从属端声明了外键属性(WorkOrder
)与主体端的主键属性匹配(Machine
)。他们不一定有相同的名字,检查一下link http://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx。因此,声明一个名为machSN
在你的WorkOrder
class:
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
and woSegments
导航属性。在一对多关系的这一侧,您不声明 FK,在另一侧,在Note
and 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
类ForeignKey
属性超过segNotes
导航属性的原因与之前解释的相同。
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; }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)