Kenci
Kenci

Reputation: 4882

How to save an object in EF context and check if it exists, without saving it to the database?

I am trying to fill up my database context and then saving all changes at the end of my loop:

 foreach (var kommune in valgkreds.Value.SubAreas)
                    {

                        var komExist = dbConnection.Omraade.FirstOrDefault(x => x.Id == kommune.Value.Id);

                        if (komExist == null)
                        {
                            Omraade k = new Omraade();
                            k.Id = kommune.Value.Id;
                            k.titel = kommune.Value.Name;
                            k.type_id = 3;
                            dbConnection.Omraade.Add(k);

                            Krydstabel_Omraade ko_kommune = new Krydstabel_Omraade();
                            ko_kommune.parent = valgkreds.Value.Id;
                            ko_kommune.child = kommune.Value.Id;

                            dbConnection.Krydstabel_Omraade.Add(ko_kommune);

                            Console.WriteLine(k.Id);
                            //Console.WriteLine(++i);
                        }
}

I am checking to see whether i have already added the object to the context with the line:

var komExist = dbConnection.Omraade.FirstOrDefault(x => x.Id == kommune.Value.Id);

It always returns null, even if the object has been added. I am guessing it is because it has not been saved to the database yet. How can i check if it is in the context before i have executed the SaveChanges() method?

Upvotes: 1

Views: 1158

Answers (1)

chrispy
chrispy

Reputation: 88

If you are using EF 4.1+, they have included a "Find" method that allows you to track down objects in your context that haven't yet been persisted to the database-

http://msdn.microsoft.com/en-US/data/jj573936

Although it looks like this will only work if you are searching using the primary key.

Upvotes: 1

Related Questions