【问题标题】:Error while adding Foreign Key from MVC Models从 MVC 模型添加外键时出错
【发布时间】:2014-04-01 05:30:00
【问题描述】:

这是我的模型

  [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”上找不到导航属性“Stationery”。名称值应该是有效的导航属性名称。

请帮忙!!

谢谢。

【问题讨论】:

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


    【解决方案1】:

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

    [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; }
    }
    

    【讨论】:

    • 谢谢,我知道了,但是在这些更改之后,我收到另一个错误消息“INSERT 语句与 FOREIGN KEY 约束“FK_dbo.Orders_dbo.Stationery_ID”冲突。冲突发生在数据库“MvcDemo1. Models.OrderDbContext”,表“dbo.Stationery”,列“ID”。语句已终止”
    • 您的外键值错误,这意味着如果您传递订单 id 0 并且该 id 在订单表中不存在,您将在插入时收到此错误
    【解决方案2】:

    尝试像这样更改代码:

    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; }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      相关资源
      最近更新 更多