【问题标题】:ForeignKey declaration in Entity Framework实体框架中的 ForeignKey 声明
【发布时间】:2014-03-29 15:38:11
【问题描述】:

我的外键有问题。

错误:类型“mvcCristal.Models.Almacen”的属性“co_art”上的 ForeignKeyAttribute 无效。在依赖类型“mvcCristal.Models.Almacen”上找不到导航属性“Articulo”。 Name 值应该是有效的导航属性名称。

我的班级宣言:

public class Articulo
{
    [Required]
    public string co_art { get; set; }
    public string des_art { get; set; }
    public string modelo { get; set; }    
    public string co_lin { get; set; }
    public string co_subl { get; set; }
    public string co_cat { get; set; }
    public string co_col { get; set; }
    [ForeignKey("co_art")]
    public ICollection<Almacen> Almacenes { get; set; }
}

public class Almacen
{
    [Key, Column(Order = 0)]
    public string co_alma { get; set; }
    public string des_alm { get; set; }
    [Required, ForeignKey("Articulo"), Column(Order = 1)]
    public string co_art { get; set; }
    public double stock_act { get; set; }
}

有什么帮助吗?谢谢;我是 EF 的新手。

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    您遇到的异常应该为您指明正确的方向,因为它明确说明了问题。它说,“导航属性 'Articulo' 未在 ...'...Almacen' 上找到。名称值应该是有效的导航属性名称。”

    好的,所以外键的 Name 值(即Articulo)需要是Almacen 上的导航属性,所以让我们这样做。

    public class Almacen
    {
        [Key, Column( Order = 0 )]
        public string co_alma { get; set; }
        public string des_alm { get; set; }
        [Required, ForeignKey( "Articulo" ), Column( Order = 1 )]
        public string co_art { get; set; }
        public double stock_act { get; set; }
        public Articulo Articulo { get; set; }
    }
    

    这样做之后,我收到另一个错误,说 co_art 需要成为 Articulo 上的键,所以我添加了它。

    public class Articulo
    {
        [Required]
        [Key]
        public string co_art { get; set; }
        public string des_art { get; set; }
        public string modelo { get; set; }
        public string co_lin { get; set; }
        public string co_subl { get; set; }
        public string co_cat { get; set; }
        public string co_col { get; set; }
        [ForeignKey( "co_art" )]
        public ICollection<Almacen> Almacenes { get; set; }
    }
    

    那时一切似乎都很幸福。

    【讨论】:

      【解决方案2】:

      您的注释看起来不正确

      您似乎想使用注释来关联一对多关系。

      Articulo 1 <--> * Almacen
      

      键和外键应该是 int 类型。

      我建议按照教程了解有关注释的更多信息,例如这些

      你也可以使用fluent api代替注解

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-23
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 2014-03-18
        • 2014-04-03
        • 2016-10-31
        • 1970-01-01
        相关资源
        最近更新 更多