C#C
C#3y ago
Messiah

❔ EFCore finding a single entry

I need to find an entry in the database or create if it doesn't exist. I can't see any mistakes in my code, yet when I process many chess matches, when an user exists in multiple matches, EF Core keeps adding multiple entries of this same user. Can you see any mistakes in this code? 4 hours of debugging this 😦

var dbAcc = null;
var playerName =entity.properties.RootElement.GetPropertyOrNull("playerName");

if (!string.IsNullOrEmpty(playerName.ToString()))
  queryAccs = queryAccs.Where(e => e.PlayerName== playerName.ToString());

dbAcc = context.Accounts.Find(queryAccs.FirstOrDefault());
if (dbAcc == null)
{
  var newAcc = new AccountEntity
    {
    playerName = playerName.ToString() ?? "error",
    };
  newAcc.ChessTeams.Add(trackedChessTeam);
  context.Accounts.Add(newAcc);
}
else{
  if (!dbAcc.ChessTeams.Contains(trackedChessTeam))
    dbAcc.ChessTeams.Add(trackedChessTeam);
}
break;
Was this page helpful?