views:

97

answers:

1

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?

+4  A: 

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.

Jon Skeet
+1 yep, this is the answer
andy
Yes, that I know. Maybe my question wasn't clear enough... I will elaborate in my question.
Svish
Is the id always 0 if not inserted? Or is it something else?
Svish