john
john

Reputation: 109

How to check if there is a record in a SQL database?

I have the following code, what i am trying to achieve is that at first i want to check if there is a record based in the database according to a condition. if the record is there it should not do anything if the record is not in it should add it in.

if (context.dBconfig.Any(c => n.Name != "John")) // here i tried to check from the database if there is no records for john it should add in  the following.If it finds a record it shouldnt do an add.
{
    context.dBconfig.Add(       
        new List.dBconfig
        {
            Name = 'John',
            address = "test"
            contact = "test"
        }
    );
}

the problem is that everytime i run the above piece of code it does an entry for john when there is already an entry in. What am I doing wrong?

Upvotes: 2

Views: 65

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460138

You want to use !Any(... == ...) instead of Any(... != ...):

if (!context.dBconfig.Any(c => n.Name == "John"))
{
  // ...
}

You are checking if there is someone who is not John instead of not someone who is John.

Upvotes: 4

Related Questions