0

I am using AspNetNet 6.

In my Page I have two [BindProperty]:

  1. tblUserToRoute Class (Entity Class)
  2. int[] SelectedRouteIds (Get Selected Item By User)

When client select several item in ListBox and click on save button, in my "OnPost" method I receive correct model and an array of selected value from ListBox which stored in "SelectedRouteIds" property. Everything is ok so far.

For save model for each selected item in ListBox I used "foreach" like below:

foreach (int item in SelectedRouteIds)
{
    tblUserToRoute.fldRouteId = item; //set selected item
    db.tblUserToRoute.Add(tblUserToRoute); //add model to repository
}
db.SaveChanges();

What I have done is: in each loop I set field value to selected item value from ListBox and then add model to context and after "foreach" loop I tried to save changes but, only one model saved to database and other model which have been passed to context not saved.

Why context cannot save multi added model? for this scenario how can I proceed?

thank you all

Hadi Mazareei
  • 31
  • 1
  • 7

1 Answers1

0

I changed my codes inside "foreach" like below:

db.tblUserToRoute.Add(new cesEntities.Models.cesUser.tblUserToRoute()
{
   fldUserId = user.fldId,

   //set item (only value which should be changed in each loop)
   fldRouteId = item, 
   fldDateExpiry = tblUserToRoute.fldDateExpiry,
   fldPermanent = tblUserToRoute.fldPermanent,
   fldValid = tblUserToRoute.fldValid,
   fldDefault = tblUserToRoute.fldDefault,
});

Now SaveChanges() method works correctly. Thank you all.

Hadi Mazareei
  • 31
  • 1
  • 7