实体框架中的 SaveChanges 插入语句外键错误
我有一个属性对象,我想从最新的存储库集合中删除它。或者我可以说在保存到数据库之前将其分离。有一个 Property
表是主表,历史记录表和详细信息表通过共享的 PropertyId
作为键与 Property
相关。当我从存储库中分离对象并尝试保存它时,会导致错误。
做这个事。
Repository.Detach(P);
错误时出错
Repository.SaveChanges();
:
INSERT 语句与 FOREIGN KEY 约束“FK_History_Property”冲突。
冲突发生在数据库“database”、表“dbo.Property”、列“PropertyId”中。
该声明已终止。
I have a property object and I wanted to delete that from the latest repository collection. Or I can say detach it before saving to the database. There is a Property
table which is main and history and detail tables are related to Property
via a shared PropertyId
as key. When I am detaching the object from the repository and trying to save it it results in an error.
Doing this.
Repository.Detach(P);
Errors out on
Repository.SaveChanges();
Error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_History_Property".
The conflict occurred in database "database", table "dbo.Property", column 'PropertyId'.
The statement has been terminated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在删除记录之前,请尝试从其他表中删除引用您要删除的记录的主键的记录。
例如:
交易表
交易详细信息
TransactionID
这里是一个外键(来自其他表的主键)。在删除事务表上的父记录之前,您必须首先删除引用其主键的所有记录,以避免外键约束错误例如:
如果您想从数据库中删除事务 1,您可以先删除交易详细信息(交易详细信息 1 和 2),然后才允许删除 transactionID 1
Try to delete records from other tables that references to the primary key of the record you are trying to delete before deleting the record.
Ex:
Transaction Table
Transaction Detail
TransactionID
here is a foreign key (Primary Key From other table). Before you could delete the parent record on transaction table you have to delete first all records that references to its PrimaryKey to avoid FOREIGN KEY CONSTRAINT ERRORSEx:
If you want to delete transaction 1 from the database, you have to delete transaction details(Transaction Detail 1 and 2) first before you will be allowed to delete transactionID 1
我认为您的意思是使用
后跟
这当然是假设您确实使用支持 DbContext 模型的 EntityFramework 的某些更高版本。
操作在存储库级别或 ObjectContext 级别进行存储库修改
在早期版本中,可以通过执行以下
I think you mean to use
followed by
This is of course assuming you are truly using some of the later versions of the EntityFramework that support the DbContext model.
In earlier versions, repository modifications could be made at the Repository level or at the ObjectContext level by doing something like
followed by