无法添加已存在的实体? [英] Cannot add an entity that already exists?

查看:120
本文介绍了无法添加已存在的实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用循环在表中插入多个记录。插入第一个记录异常后生成。

错误: - 无法添加已存在的实体?



以下是我的代码。



解决了 -



I am inserting multiple records in my table using loop. After insert first record exception Generates.
ERROR:- Cannot add an entity that already exists?

Below is my Code.

Solved-

 PromoCodeForSpecificBook1 obj;
foreach(var i in Model.BookDetail)
                      {
   obj = new PromoCodeForSpecificBook1();
                          obj.BookId = i.ID; //Convert.ToInt32(Model.Id);
                          var P = DB.BookPromoCodes.OrderByDescending(X => X.Id).FirstOrDefault().Id;
                          obj.PromoCodeId =P;
                          DB.PromoCodeForSpecificBook1s.InsertOnSubmit(obj);
                          DB.SubmitChanges();



                        
                      }

推荐答案

1.为了在数据库中添加新记录,你必须在foreach循环中创建新对象。



2.A第二个问题是你正在阅读相同的预订促销代码对于每个项目,应该只读取foreach之前的内容。



3.第三个优化可能是保存所有更改只在foreach结束时。



修改后的源代码应该是:

1.In order to add new records in the database you have to create new objects in your foreach loop.

2.A 2nd problem is the fact that you are reading the same booking promo code for each item and should be read only ones before the foreach.

3.A 3rd optimisation could be to save all changes only ones at the end of the foreach.

The modified source code should be:
var P = DB.BookPromoCodes.OrderByDescending(X => X.Id).FirstOrDefault().Id;
foreach(var i in Model.BookDetail)
                      {
                          PromoCodeForSpecificBook obj = new PromoCodSpecificBook(); //Create your entity!
                          obj.BookId = i.ID;
                          obj.PromoCodeId =P;
                          DB.PromoCodeForSpecificBooks.InsertOnSubmit(obj);
                      }
DB.SubmitChanges(); //Save all changes in a single call!


这篇关于无法添加已存在的实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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