如何避免System.Data.Entity.Infrastructure.DbUpdateException [英] How to avoid System.Data.Entity.Infrastructure.DbUpdateException

查看:2252
本文介绍了如何避免System.Data.Entity.Infrastructure.DbUpdateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包括本的DbContext对象 -

   - 员工
- 公司地址(PK:AddressFirstLine,市)
注:一个员工可以有很多的公司地址

记录添加到公司地址表中的仅在的一些地址不存在于表公司地址。结果
。如果我有一个从数据库中的两个的DbContext对象说Snapshot1,Snapshot2。
说,当被带到这两个快照,有在表公司地址没有记录。
当更改了Snapshot1制作并保存 - 记录写入表公司地址结果
当更改了Snapshot2制成,使用



<扑出pre> mydataContext.SaveChanges();

出现

例外:

  System.Data.Entity.Infrastructure.DbUpdateException:PRIMARY KEY约束'PK_CompanyAddress违反:更新条目
System.Data.SqlClient.SqlException发生错误。不能插入对象dbo.CompanyAddress'
重复键



这似乎节约Snapshot1制成Snapshot2脏的,因为当它们被保存回数据库中,都有过的相同的公司地址的记录。



我可以做的DbContext对象上有什么其他的呼叫/设置,以避免该错误?



感谢您!


解决方案

您错误啥都没做的的DbContext对象。你的问题是,你试图插入具有复制主键的记录。 ,这是你的异常消息说什么



看你如何建立你的公司地址对象,什么是当您保存它们的钥匙 - 这会给你的线索



编辑:,这是一个坏主意,有主键是一个自然的关键,即你不应该将城市和地址作为主键。你应该有任何GUID或整型是主键不依赖于存储在数据库中的信息。



和强制执行唯一性,保存到数据库之前,你是否该记录存在,并且可以添加一个唯一索引基于独特的约束数据库表。


I have this DbContext object which consists of -

- Employee
- CompanyAddress  (PK: AddressFirstLine, City)
Note: one Employee can have many CompanyAddress

Records are added to CompanyAddress table only if some address doesn't exists in CompanyAddress table.
If I have two DBContext objects from database say Snapshot1, Snapshot2. Say when both these snapshots were taken, there were no records in CompanyAddress table. When changes were made to Snapshot1 and saved - records are written to CompanyAddress table.
When changes were made to Snapshot2 and saved using

mydataContext.SaveChanges();

exception occurs:

System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries
System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_CompanyAddress'. Cannot insert duplicate key in object 'dbo.CompanyAddress'

It seems saving of Snapshot1 made Snapshot2 dirty because when they are saved back to database, both had same CompanyAddress records.

What other call/settings I can make on dbContext object to avoid this error?

Thank you!

解决方案

Your error has got nothing to do with the DbContext objects. Your problem is that you are trying to insert a record with duplicating primary key. That is what your exception message says.

Look at how you create your CompanyAddress objects and what are the keys when you save them - this will give you the clues.

Edit: And it is a bad idea to have primary key to be a natural key, i.e. you should not assign city and address as primary keys. You should have either Guid or Integer to be primary key that is not dependent on the information stored in DB.

And to enforce uniqueness, before you save to DB, you check if that record exists, and can add a unique index to database table based on the unique constraints.

这篇关于如何避免System.Data.Entity.Infrastructure.DbUpdateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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