如何使用LINQ在foreach命令中插入多行? [英] How to Insert Multiple Rows in a foreach command with LINQ?

查看:144
本文介绍了如何使用LINQ在foreach命令中插入多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下几行:

foreach (var catId in CatIds)
{
    AdCategory.AdId = LastAd.AdID;
    AdCategory.CategoryId = catId;
    EngineDB.Ad_Categories.InsertOnSubmit(AdCategory);
    EngineDB.SubmitChanges();
}


CatIds是一个整数数组.
此命令正确插入第一个元素,但下一个循环会导致此异常:
无法添加已经存在的实体."
我该如何解决.
请尽快帮助我!


and CatIds is an Integer Array.
this command inserts first element correctly but next loop causes this exception:
"Cannot add an entity that already exists."
How can I fix it.
please help me as soon as posible!

推荐答案

您需要在循环中创建一个新的AdCategory.否则,由于错误状态,您打算一次又一次地插入同一对象.

You need to create a new AdCategory in the loop. Otherwise, as the error states, you are tyring to insert the same object again and again.

您还应该移动

EngineDB.SubmitChanges();

在循环之外,因此您只需对数据库进行1次调用.

outside of the loop so you only make 1 call to the database.

这篇关于如何使用LINQ在foreach命令中插入多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆