开发者

SaveChanges in Entity Framework insert statement foreign key error

开发者 https://www.devze.com 2023-04-13 08:56 出处:网络
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 an

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.Sav开发者_Go百科eChanges();

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.


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

TransactionID DateOfTransaction CustomerID
1             11/15/11          1
2             11/15/11          2
3             11/15/11          15
4             11/15/11          3

Transaction Detail

TransactionDetailID TransactionID ItemID Quatity
1                   1             43     15
2                   1             32      2
3                   2             43     89
4                   4             32     12

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 ERRORS

Ex:

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


I think you mean to use

Repository.DeleteObject(P);

followed by

ObjectContext.SaveChanges();

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

ObjectContext.DeleteObject(P);

followed by

ObjectContext.SaveChanges();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号