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 FirstOrDefault
instead of First
, that will return null
if there are no matches.
As for knowing whether you need to insert - just remember whether or not it was null to start with:
var a = dataContext.Things.FirstOrDefault(x => x.Name == something);
bool needsInsertion = (a == null);
a = a ?? new Thing { Name = something };
Alternatively, if there's an ID field in Thing
which is automatically populated by the database, you can just use that to detect whether it's already in the database or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With