C
C#15mo 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;
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;
5 Replies
Tvde1
Tvde115mo ago
let's work this backwardsly(?) dbAcc is null, because only then it will add new accounts. dbAcc does context.Accounts.Find(). I think it's good to look at the documentation again to see what this method does again. The input to Find() is queryAccs.FirstOrDefault() Find() takes the key and will find the corresponding entity. Is queryAccs.FirstOrDefault() a key?
Messiah
MessiahOP15mo ago
I actually just realized why this is happening. The transaction is only sent after my code loops through everything, so it will always return not found is there a way to force transactions within a single ef core lifetime?
Tvde1
Tvde115mo ago
I doubt you'll need transactions
JakenVeina
JakenVeina15mo ago
I'm not even sure what this is supposed to mean
Accord
Accord15mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server