使用linq将列表附加到db到sql [英] Attach list to db with linq to sql
问题描述
我的问题是我试图将一个 List<>
附加到数据库的表中。此列表中的某些项目包含主键 - 这些项目应视为数据库的UPDATES。某些项目没有主键 - 这些项目应该插入数据库。
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.
我试过
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?
我在两年前发现了同样的问题 - 使用AttachAll的Linq To Sql 。DuplicateKeyException ,其中的答案基本上是我的解决方案,新实体6和过去两年所添加的所有新东西现在有一种方法来做我想做的事情? / p>
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?
推荐答案
http://msdn.microsoft.com/en-us/library/hh846520(v = vs103).aspx
你需要使用ObjectContext而不是DbContext我认为这取决于你如何构建你的上下文。
You need to using ObjectContext though rather than DbContext i think so it depends how you built your context.
这篇关于使用linq将列表附加到db到sql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!