简体   繁体   中英

How to add Entity Model containing a list of another Entity Model type to Database with EF using lambda expressions and linq

I've got an Entity Model containing a list that is type of another Entity model, I need to add a record with a list of the other model to the Database at once a null reference exception occurs when I'm adding each prop to prop list with ForEach

        public IActionResult RegisterUnitConfirm(InventoryItemUnitViewModel model)
        {
            if (ModelState.IsValid)
            {
                InventoryItemUnit unit = new InventoryItemUnit()
                {
                    Title = model.Title,
                    Item_Id = model.Item_Id,
                };
                model.Props.ForEach(x => unit.Props.Add(new InventoryItemUnitProp()
                {
                    Name = x.Name,
                    Value = x.Value,
                    Category_Id = x.Category_Id,
                }));
                DB.Add(unit);
                if (DB.SaveChanges() != 0)
                {
                    TempData["GlobalSuccess"] = "";
                    return RedirectToAction("UnitSummery");
                }
                TempData["GlobalError"] = "";
                return RedirectToAction("UnitSummery");
            }
            TempData["GlobalError"] = "Model State is invalid";
            return RedirectToAction("UnitSummery");
        }

you should create new Props when create new unit

like this :

InventoryItemUnit unit = new InventoryItemUnit()
                {
                    Title = model.Title,
                    Item_Id = model.Item_Id,                       
  Props=new List<Props>() 
                };

I hope it will be useful

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