MVC5模型没有链接

时间:2015-09-15 11:14:00

标签: asp.net-mvc

我做了一个分类模型和一个产品模型。 当我支持这两个时,我希望在我的产品模型上下载所有类别。

然而,当我的产品模型上的这两个模型脚手架时,我得到一个类别ID,它是一个int。不是我的类别下拉。

类别:

    public class Category
{
    #region properties
    [Key]
    public int Id { get; set; }

    [DisplayName("Category")]
    [Required(ErrorMessage = "You need to enter a category")]
    public string Name { get; set; }
    #endregion
}

产品:

    public class Product
{
    #region properties
    [Key]
    public int Id { get; set; }

    [Required(ErrorMessage = "An Item Name is required")]
    [StringLength(160)]
    public string Name { get; set; }

    public string Description { get; set; }

    [Required(ErrorMessage = "Price is required")]
    [Range(0.01, 999.99, ErrorMessage = "Price must be between 0.01 and 999.99")]
    public decimal Price { get; set; }

    public int CatagorieId { get; set; }
    public virtual Category Category { get; set; }
    #endregion
}

1 个答案:

答案 0 :(得分:1)

只需在类别

上添加FK属性即可
  using System.ComponentModel.DataAnnotations;
  using System.ComponentModel.DataAnnotations.Schema;

  public class Product
  {

        [Key]
        public int Id { get; set; }

        [Required(ErrorMessage = "An Item Name is required")]
        [StringLength(160)]
        public string Name { get; set; }

        public string Description { get; set; }

        [Required(ErrorMessage = "Price is required")]
        [Range(0.01, 999.99, ErrorMessage = "Price must be between 0.01 and 999.99")]
        public decimal Price { get; set; }

        public int CatagorieId { get; set; }

        [ForeignKey("CatagorieId")]
        public virtual Category Category { get; set; }

    }