实体使用现有ID添加新ID

时间:2017-04-04 23:34:33

标签: c# asp.net entity-framework list

如何在没有空引用错误的情况下附加整个列表或循环遍历它?

实体类

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();
    }

1 个答案:

答案 0 :(得分:0)

var categories = prodCat
    .Select(p => new Category
    {
        Category_ID = p.Value,
        Category_Name = p.Text
    }
    .ToList();