skip to Main Content

I have a variable which is IQueryable and I have parameter in my viewmodel that it shows a differences between my selected day and today the code is:

public async Task<ResultData<HomePlannedRecieptInfo>> GetHomePlannedReciepts(HomePlannedRecieptQuery query)
{
    var datelist = new List<DateTime>();
    var date = DateTime.Now;
    for (var i = 0; i <= 6; i++)
    {
        datelist.Add(date.AddDays(i));
    }
    datelist.Add(date);

    IQueryable<HomePlannedRecieptInfo> result = context.HomePlannedRecieptInfos.Where(t=>t.Date >= DateTime.Today);
      
    foreach (var item in result.ToList())
    {
        item.DayDiff = (item.Date.Date - DateTime.Now.Date).TotalDays.ToString();
    }

    var offset = (query.PageNumber - 1) * query.PageSize;
    var psize = query.PageSize;
    var countQuery = await result.CountAsync();
    var data = result.OrderByDescending(c => c.Date);

    return new ResultData<HomePlannedRecieptInfo>
    {
        CurrentPage = query.PageNumber,
        TotalItems = countQuery,
        PageSize = query.PageSize,
        Data = data.ToList()
    };

when I execute the code in foreach I can see the number of days in item.dayDiff but I can’t see it when the the data return. Can somebody help me please?

2

Answers


  1. You’re calling result.ToList(), but you’re just iterating over it in the foreach loop, you’re not actually storing it anywhere. This should fix it:

       var resultAsList = result.ToList();
       foreach (var item in resultAsList)
        {
            item.DayDiff = (item.Date.Date - DateTime.Now.Date).TotalDays.ToString();
        }
    
    
        ...
        var data = resultAsList.OrderByDescending(c => c.Date);
    
    Login or Signup to reply.
  2. That is because every time you materialize a IQueryable the data is taken from the database. You materializing twice in your code. Once in the foreach and once when returning the data in data.ToList(). Hence you have two lists with different items. Since you are changing the data in the first list the second will not receive that data.

    You have two possibilities:

    • Call ToList before the foreach and use the same materialized list for changing the property and returning the same list
    • Change the get acessor for DayDiff to following public string DayDiff {get => (Date.Date - DateTime.Now.Date).TotalDays.ToString();} Using this has the advantage that you do not have to remind you to set the DayDiff if you query the data on other locations of your code
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search