my problem is that I am trying to attach a List<>
into a table in the database. Some items in this List<> contain a Primary Key - these items should be treated as UPDATES to the database. Some items do not have a primary key - these items should be INSERT into the db.
i Tried
Context.myTable.AttachAll(myList, true);
Context.myTable.AttachAll(myList, false);
Context.myTable.AttachAll(myList);
all do not work. So then I do something like:
var listFromDb = Context.myTable.Where(x => myListOfIds.contains(x.primaryKey));
foreach (var obj in myList)
{
if(obj.primaryKey > 0)
{
Context.myTable.Attach(obj, listFromDb.FirstOrDefault(x => x.primaryKey == obj.primaryKey);
}
else{
Context.myTable.InsertOnSubmit(obj);
}
Context.SubmitChanges();
}
there has to be an easier way then iterating through each item in the list and manually deciding weather or not to do Attach or Insert. Is there something that I am missing here?
EDIT
I found this same question from almost 2 years ago - Linq To Sql using AttachAll. DuplicateKeyException , the answer in it is basically what my solution was. With the new Entities 6 ,and all the new things added in the past 2 years is there now a way to do what I am trying to do?
I don't know if there is a better solution but I think this will work fine:
And by this way you don't need to get all old items from the Database.
http://msdn.microsoft.com/en-us/library/hh846520(v=vs.103).aspx
You need to using ObjectContext though rather than DbContext i think so it depends how you built your context.