从MVC模型添加外键时出错

时间:2014-04-01 05:30:00

标签: sql-server asp.net-mvc asp.net-mvc-4

以下是我的模特

  [Table("Stationery")]
public class Stationery
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
}

[Table("Orders")]
public class Order
{
    [Key]
    public int CustomerID { get; set; }
    [ForeignKey("Stationery")]
    public int ID { get; set; }
    public int Quantity { get; set; }
}

在将控制器添加到订单时,我收到以下错误...

说:

  

无法检索Models.Order的元数据。 “Models.Order”类型上属性“ID”的外键属性无效。在依赖类型“Models.Order”上找不到导航属性“文具”。名称值应该是有效的导航属性名称。

请帮助!!

谢谢。

2 个答案:

答案 0 :(得分:0)

尝试更改代码:

public class Stationery
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual IList<Order> Orders { get; set; }
}

public class Order
{
    [Key]
    public int CustomerID { get; set; }
    public virtual Stationery Stationery { get; set; }
    public int Quantity { get; set; }
}

答案 1 :(得分:0)

像这样创建你的模型来添加关系,你们俩都不知道这种关系,如果它是一对一的关系,这将有效:

[Table("Stationery")]
public class Stationery
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
    public Order Order {get;set;}
}

[Table("Orders")]
public class Order
{
    [Key]
    public int CustomerID { get; set; }
    [ForeignKey("Stationery")]
    public int ID { get; set; }
    public int Quantity { get; set; }
    public virtual Stationery Stationery { get; set; }
}

如果关系是一对多,那么这样做:

[Table("Stationery")]
public class Stationery
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
    public ICollection<Order> Orders {get;set;}
}

[Table("Orders")]
public class Order
{
    [Key]
    public int CustomerID { get; set; }
    [ForeignKey("Stationery")]
    public int ID { get; set; }
    public int Quantity { get; set; }
    public virtual Stationery Stationery { get; set; }
}