Svish
Svish

Reputation: 158091

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?

Upvotes: 5

Views: 168

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500923

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.

Upvotes: 4

Related Questions