【问题标题】:Error: ForeignKeyAttribute on property is not valid错误:属性上的 ForeignKeyAttribute 无效
【发布时间】:2019-09-14 12:49:25
【问题描述】:

我正在尝试使用实体框架从数据库中“获取”一个实体——它与另一个实体具有一对一的关系。 ContactModel 上有一个名为“ImageId”的外键,但我收到此错误:

'类型上属性'Image'上的ForeignKeyAttribute “Models.ContactModel”无效。外键名称“ImageId”是 在依赖类型“Models.ContactModel”上找不到。名称值 应该是逗号分隔的外键属性名称列表。'

我显然做错了什么,但不知道是什么。

这些是我的实体类:

 [Table("Contact")]
public class ContactModel
{
    public int Id { get; set; }

    [Required]
    public string  Name { get; set; }

    [Required]
    public string Phone { get; set; }


    public string Email { get; set; }

    [ForeignKey("ImageId")]
    public virtual ImageModel Image { get; set; }
}

[Table("ContactImage")]
public class ImageModel
{
    public int Id { get; set; }

    public byte[] Image { get; set; }
}

任何建议将不胜感激。

谢谢!

【问题讨论】:

    标签: c# entity-framework asp.net-web-api


    【解决方案1】:

    如果我没记错的话,你应该在 ContactModel 类上有一个外键属性和一个图像本身的属性。

    像这样:

    [Table("Contact")]
    public class ContactModel
    {
        public int Id { get; set; }
    
        [Required]
        public string  Name { get; set; }
    
        [Required]
        public string Phone { get; set; }
    
    
        public string Email { get; set; }
    
        //Foreign key for Image
        public int ImageId { get; set; }
    
        [ForeignKey("ImageId")]
        public virtual ImageModel Image { get; set; }
    }
    
    [Table("ContactImage")]
    public class ImageModel
    {
        public int Id { get; set; }
    
        public byte[] Image { get; set; }
    }
    

    对于您当前的模型,您是说 ContactModel 有一个 ImageModel 类型的 Image,并且它有一个名为 ImageId 的外键,但该外键不存在。

    【讨论】:

      【解决方案2】:

      您应该在 Contact Model 中为 FK ID 添加另一个属性,并使用 FK 属性对其进行装饰,例如:

      [Table("Contact")]
      public class ContactModel
      {
          public int Id { get; set; }
      
          [Required]
          public string  Name { get; set; }
      
          [Required]
          public string Phone { get; set; }
      
      
          public string Email { get; set; }
      
          [ForeignKey("Image")]
          public int ImageId { get; set; }
      
          public virtual ImageModel Image { get; set; }
      }
      

      【讨论】:

        【解决方案3】:

        https://www.learnentityframeworkcore.com/configuration/data-annotation-attributes/foreignkey-attribute 它有几种表示外键的方法。我发现在依赖类中指示 [ForeignKey("ClassName")] 在 MVC5 中不起作用。

        【讨论】:

          猜你喜欢
          • 2012-08-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-08-19
          相关资源
          最近更新 更多