[英]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 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.