【发布时间】:2015-03-02 21:58:16
【问题描述】:
我正在尝试使用EF page at Data Developer Center、相关 SO 答案here、另一个 SO 线程 here 和 this article 中概述的技术为“代码优先”方法设置 EF 类在 CodeProject.com。
两个类需要使用数据注释进行一对多交互,特别是外键。
我的课程似乎一切都井井有条。我可以执行context.Add(),但是通过context.SaveChanges() 保存更改时,我收到以下错误消息:
类型上属性“机器”上的 ForeignKeyAttribute “BacklogTracker.Models.EFModels.Customer”无效。外国的 在依赖类型上找不到键名“MachID”。
为什么会出现此错误?
根据本问题开头链接中概述的示例和技术,我的 EF 类和外键似乎是有序的……但我不知道出了什么问题。我是这方面的初学者,所以很可能我完全错过了一些东西。
我正在使用 VS2013 Express、.NET 框架 4.5、EF 6.1.2。这是类的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Customer
{
public Customer()
{
Machines = new List<Machine>();
}
[Key]
public int Number { get; set; }
public string Name { get; set; }
public string MachID { get; set; }
[ForeignKey("MachID")]
public virtual List<Machine> Machines { get; set; }
}
和
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Machine
{
public Machine()
{
Customer = new Customer();
}
[Key]
public string SN { get; set; }
public string Model { get; set; }
public int Hours { get; set; }
public string Location { get; set; }
public int CustID { get; set; }
[ForeignKey("CustID")]
public virtual Customer Customer { get; set; }
}
【问题讨论】:
标签: c# asp.net entity-framework