I would like to check if an entity is already added to the database. So, how can I see this difference between a and b?
var a = dataContext.Things.First(x => x.Name == something);
var b = new Thing { Name = something };
To make it clearer, if I have this:
var thing = dataContext.Things.FirstOrDefault(x => x.Name == something)
?? new Thing { Name = something };
How can I see if thing needs to be inserted?
If you use
FirstOrDefaultinstead ofFirst, that will returnnullif there are no matches.As for knowing whether you need to insert – just remember whether or not it was null to start with:
Alternatively, if there’s an ID field in
Thingwhich is automatically populated by the database, you can just use that to detect whether it’s already in the database or not.