none
A simple add to list from an ApplicationUser : IdentityUser RRS feed

  • Question

  • I have these classes for EF. It is vary simple as you can see in a fresh template.

        public class ApplicationUser : IdentityUser
        {
            public List<Payment> Payments { get; set; }
        }
    
        public class Payment
        {
            public int Id { get; set; }
            public virtual ApplicationUser User { get; set; }
            public string UserId { get; set; }
    
            public int Total { get; set; }
        }

    Now I just want to add one new row into my payment table that is associated to the logged in user.

            public async Task<ActionResult> AddFunds()
            {
                var user = await GetCurrentUserAsync();
                if (user != null)
                {
                    user.Payments.Add(new Payment { Total = 10 });
    
                    await _userManager.UpdateAsync(user);
    
                    return RedirectToAction(nameof(Index));
                }
    
                return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
            }

    It does not create a break exception in Visual Studios instead it give me the error page instead.

    You would think this would just work. I have to be missing something small.


    MSDN jbeen19

    Wednesday, June 8, 2016 4:14 AM

Answers

  • Maybe GetCurrentUserAsync returns an object having a null Payments property. Check if GetCurrentUserAsync works as expected and make sure that Payments is not null. For example, assign ‘new List<Payment>()’ to Payments, probably inside GetCurrentUserAsync. Also check the _userManager member.


    • Edited by Viorel_MVP Wednesday, June 8, 2016 6:39 AM
    • Marked as answer by jbeen19 Wednesday, June 8, 2016 7:02 AM
    Wednesday, June 8, 2016 6:37 AM

All replies

  • Maybe GetCurrentUserAsync returns an object having a null Payments property. Check if GetCurrentUserAsync works as expected and make sure that Payments is not null. For example, assign ‘new List<Payment>()’ to Payments, probably inside GetCurrentUserAsync. Also check the _userManager member.


    • Edited by Viorel_MVP Wednesday, June 8, 2016 6:39 AM
    • Marked as answer by jbeen19 Wednesday, June 8, 2016 7:02 AM
    Wednesday, June 8, 2016 6:37 AM
  • I cannot believe that was it. I have used LINQ to SQL which never required me to set it as a new List<t>().  The rest of the code works as expected. Thank you.

    MSDN jbeen19

    Wednesday, June 8, 2016 7:10 AM