Attach list to db with linq to sql

2019-07-21 10:11发布

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?

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-21 11:01

I don't know if there is a better solution but I think this will work fine:

foreach(var item in myList)
{
   if(item.Id > 0)
      context.Entry(item).State = EntityState.Modified;          
   else
      context.Table.Add(item);
}

And by this way you don't need to get all old items from the Database.

查看更多
混吃等死
3楼-- · 2019-07-21 11:10

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.

查看更多
登录 后发表回答