Problem while updating a child list in C # ASP.Net MVC

Refresh

February 2019

Views

0 time

1
public class PayRateDaysModel   
{
    public string day_name { get; set; }
    public List<RateList> multiplier { get; set; }
}
public class RateList
{
    public double start_after { get; set; }
    public double rate_multiplier { get; set; }
}

daysModel is a List of type PayRateDaysModel. When I'm trying to update multiplier in current object of daysModel list i.e. dayExists, then its updating multiplier in all the elements of daysModel list. I want to update only in current item.

Below is my code :

var dayExists = daysModel.Where(x => x.day_name == day_name).FirstOrDefault();

if(dayExists==null)
{
    PayRateDaysModel days = new PayRateDaysModel();
    days.day_name = day_name;
    days.multiplier = rate_list;
    daysModel.Add(days);
}
else
{
    //update
    dayExists.day_name = "abc";               
    dayExists.multiplier.FirstOrDefault().rate_multiplier = 1;

}

2 answers

0

I don't see any reason for it not to work. Are you sure you are testing it in right way?

I think it will be better to improve the code and test for null value :

    var dayExists = daysModel.Where(x => x.day_name == day_name).FirstOrDefault();
        if(dayExists==null)
        {
               PayRateDaysModel days = new PayRateDaysModel();
               days.day_name = day_name;
               days.multiplier = rate_list;
               daysModel.Add(days);
        }
        else
        {
           //update
           dayExists.day_name = "abc";     
          var firstMultiplier= dayExists.multiplier.FirstOrDefault();
          if( firstMultiplier!=null)
          { 
              firstMultiplier.rate_multiplier = 1;
          }

         }
1

Based on what you have shown to us I would think that you are creating the rate_list somewhere above like rate_list = new RateList(…) and you are setting this to all of your days in days.multiplier = rate_list;. Since you did not recreate that rate_list for every element, any time you change it in one of your dayExists you will change it for all the others as well. So you should do something like this days.multiplier = new RateList(…);

Check this link : Updating child items in List updates all Items in C#