Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: How to see if a Linq2SQL entity is in the database

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?

like image 409
Svish Avatar asked Oct 14 '22 15:10

Svish


1 Answers

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.

like image 200
Jon Skeet Avatar answered Oct 20 '22 17:10

Jon Skeet