0

I have a challenge that I have searched online couldn't find an answer for it. I have a class which I create a list from:

public class PairingList
   {
    public int PlayerId { get; set; }
    public int OpponentId { get; set; }
   }
var getAll = await _db.TblResult.ToListAsync();
        foreach (var row in pairingList)
        {
            getAll.FirstOrDefault(a =>a.Id==row.PlayerId).Round1_Opp 
            = row.OpponentId;
             getAll.FirstOrDefault(a 
          =>a.Id==row.OpponentId).Round1_Opp = row.PlayerId;
        }

        _db.Update(getAll);
        _db.SaveChangesAsync();

I get all of the results from db and would like to update based on pairingList and save into the db.

After the compiling code I get following error:

NullReferenceException: Object reference not set to an instance of an object.

Tân
  • 1
  • 15
  • 56
  • 102
Adam
  • 1
  • What's the type of `pairingList`? It can't be `PairingList`; that's not a collection, it's a type with two integer properties – Flydog57 Dec 25 '19 at 02:28
  • 1
    I really doubt you get a null reference exception *"after compiling the code"*. Perhaps you get it when you try to run your code? You'd be surprised at how effective it is to write up a very good SO question; one where you check and double check your code, where you recreate the problem exactly so that you can describe it to anyone. If you check my history, you'll see that I've never asked an SO question. I've started twice, but each time, after spending an hour or two getting the question just right, I figured out the answer – Flydog57 Dec 25 '19 at 02:37
  • I was getting the list of the users and trying to pair them up. If I had an odd number of the player I added an Id number which was not in the user list. I was not checking if the linq query returns null or not. – Adam Dec 27 '19 at 21:49

1 Answers1

0

You are trying to access property after FirstOrDefault()

getAll.FirstOrDefault(a =>a.Id==row.PlayerId).Round1_Opp 

Problem here that FirstOrDefault may return null if condition was not met. You need to add a null check statement before accessing this property, for example:

var item = getAll.FirstOrDefault(a =>a.Id == row.PlayerId);  
if (item != null)
{
    item.Round1_Opp = row.OpponentId;
} 
Roman.Pavelko
  • 1,555
  • 2
  • 15
  • 18
  • 1
    Thank you! you are right I was not checking if Item is null or not. I was adding an Id to the list if I have odd numbers of the players. It was trowing an error because of the manually entered Id which is not in the user list. – Adam Dec 27 '19 at 21:46