繁体   English   中英

实体添加新ID而不是使用现有ID

[英]Entity adds new IDs instead using existing one

如何附加整个列表或遍历整个列表而没有空引用错误?

实体类

public class Product
    {
        [Key]
        public int Product_Id { get; set; }
        public string Product_Name { get; set; }
        public IList<Category> Categories { get; set; }       
    }

public class Category
    {
        [Key]
        public int Category_ID { get; set; }
        public string Category_Name { get; set; }
        public IList<Product> Products { get; set; }
    }

CheckBoxList中的列表

 IList<ListItem> prodCat = new List<ListItem>();
    foreach (ListItem item in cblCategory.Items)
    {
        if (item.Selected)
        {
            prodCat.Add(item);
        }
    }

新增产品

我尝试附加类别-查看评论

        public void AddProduct(string prodName, IList<ListItem> prodCat)
    {
        ProductDBContext productDBContext = new ProductDBContext();
        Product prodNew = new Product();
        prodNew.Product_Name = prodName;

        List<Category> categList = new List<Category>();
        foreach (ListItem item in prodCat)
        {
            Category categObj = new Category
            {
                Category_Name = item.Text,
                Category_ID = Convert.ToInt32(item.Value)
            };
            categList.Add(categObj);
          //  prodNew.Categories.Add(categObj);  //Null reference
        }
        prodNew.Categories = categList;
        productDBContext.Products.Add(prodNew);
        productDBContext.SaveChanges();
    }
var categories = prodCat
    .Select(p => new Category
    {
        Category_ID = p.Value,
        Category_Name = p.Text
    }
    .ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM