简体   繁体   中英

Entity adds new IDs instead using existing one

How can I attach entire list or loop through it without null reference error?

Entity classes

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

List from CheckBoxList

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

Adding new product

I've tried to attach Categories - see comment

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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