首页 > 解决方案 > 将模型添加到实体

问题描述

我是 EF 的新手。我的问题是我想将Category模型添加到产品(实体)。

但事实证明,当我添加新产品时,EF 正在添加另一个类别。

public class Category
{
    public int Id { get; set; }

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

    public bool isActive { get; set; } = true;

}

public class Product
    {
        public int Id { get; set; }

        public Category Category { get; set; }

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

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

        public string Description { get; set; }

        [Required]
        public int ROP { get; set; }

        [Required]
        public int EOQ { get; set; }

        public bool isActive { get; set; } = true; 
    }


            var prodcategory = gridView2.GetFocusedRow() as Category;
            context.Categories.Attach(prodcategory);
            context.Products.Add(new Product
            {
                Name = name,
                Barcode = barcode,
                Description = description,
                ROP = rop,
                EOQ = eoq,
                Category = prodcategory
            });

标签: entity-framework

解决方案


修复您的 dbcontext 类:

public class Category
{
    public Category()
    {
     Products = new HashSet<Product>();
     }
    [Key]
    public int Id { get; set; }

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

    public bool isActive { get; set; } = true;

     InverseProperty(nameof(Product.Category))]
     public virtual ICollection<Product> Products{ get; set; }
}

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

        public int CategoryId { get; set; }

        [ForeignKey(nameof(CategoryId))]
        [InverseProperty("Categories")]
        public  virtual Category Category { get; set; }

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

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

        public string Description { get; set; }

        [Required]
        public int ROP { get; set; }

        [Required]
        public int EOQ { get; set; }

        public bool isActive { get; set; } = true; 
    }

在此之后,您可以保存类别:

            var prodcategory = gridView2.GetFocusedRow() as Category;
            context.Products.Add(new Product
            {
                Name = name,
                Barcode = barcode,
                Description = description,
                ROP = rop,
                EOQ = eoq,
                Category = prodcategory
               });
             contex.SaveChanges();

推荐阅读