我的问题是,我试图附加名单,其中;>
成数据库中的表。在这个名单,其中有些项目;>包含一个主键 - 这些项目应被视为对数据库的更新。有些项目没有一个主键 - 这些项目应插入到数据库
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?
我发现这个同样的问题,几乎2年前 - Linq到SQL使用AttachAll。 DuplicateKeyException ,它的答案基本上是我的解决办法了。随着新的实体6,和所有的新事物,在过去的2年增加为现在有一个办法做我想要做什么?
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 = vs.103)的.aspx
您需要使用的ObjectContext虽然而非的DbContext我想是这样这取决于你如何建立你的环境。
You need to using ObjectContext though rather than DbContext i think so it depends how you built your context.