0

I've been looking for a answer for this for a while, but can't really find one, or understand. I'm using Entity Framework in my ASP.NET 4.5 C# Web Forms application - working with the code first model.

So far I've only done some simpler things, like adding new data to a database using objects, but now I'm facing a problem where I'm stuck.

This is how I have been working so far with EF, as I wrote above, just adding data right away.

myContext.myObject.Add(object);
myContext.SaveChanges();

What I want to do now however is only add new data. What I mean here is for example, if i have a list containing 10 objects and all of these objects have already been inserted to the database, I want them to be ignored when adding the same list again. But, if the list has received new objects, say for example I now have the 10 objects since before, and 5 new. I want the 5 new ones to be added, and the 10 that are already in my db, to be ignored.

So far I'm thinking that this can only be achieved using LINQ in some way? But how?

Thanks a lot in advance for any help i can get!

Subtractive
  • 500
  • 2
  • 9
  • 19
  • What is your criteria you use to determine what is "already inserted" ? A unique ID ? Int, Guid, etc. ? – Francis Ducharme Apr 25 '14 at 15:24
  • Hi! My criteria is a string/vchar(200) called "title" and a int foreign key called "mainID". So for every "mainID" - there must be unique "title"s. – Subtractive Apr 25 '14 at 15:26
  • As you've guessed, the only way to do it is through LINQ and see if anything comes back http://stackoverflow.com/questions/9287454/check-the-existence-of-a-record-before-inserting-a-new-record – Francis Ducharme Apr 25 '14 at 15:27
  • Thank you! This answer in the thread you linked: http://stackoverflow.com/a/9287496/3257261 solved my problem, all is now working very well! :) – Subtractive Apr 25 '14 at 15:51

1 Answers1

0

Use linq to check if the object already exists in your DB before you add it

foreach(var obj in customObjects)
{
  if(!myContext.myObjects.Any(o => string.Equals(o.title, obj.title, StringComparison.OrdinalIgnoreCase)))
  {
    myContext.myObject.Add(obj);
  }
}

myContext.SaveChanges();

I suggest you use an ID field on your 'myObject' and check if it's > 0 instead of searching a string value throughout your database.

mambrow
  • 442
  • 5
  • 14
  • Thank you! This answer together with the answer given here: http://stackoverflow.com/a/9287496/3257261 solved my problem! Too bad i don't have 15 in rep yet, would have given you both upvotes if I could. :) – Subtractive Apr 25 '14 at 15:52