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

333 views Asked by At

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

1

There are 1 answers

1
masoud On BEST ANSWER

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