简体   繁体   中英

EF6 Updating 3 tables in one go

I have a database with 3 tables

Table Customer

CustomerID  (PK)

Name

Table Order

OrderID       (PK)

CustomerID    (FK)

OrderDate

Table OrderDetailLine

OrderDetailLineID

OrderID       (FK)

Price

ProductCode

What I would like to do in the Entity Framework is add 1 customer, then add several different Orders, each with many OrderDetailLine all relating to the first customer inserted. I have hooked up all the relationship in SQL Server and imported them into EF model. All no problems. I can insert 1 customer and many orders and OrderDetailLine first time all records get inserted ok into the correct databse tables

I am looping around customer and orders in a file adding then adding the customer and orders to the database

But when I want to add another order for the same customer( I am getting a Primary key violation on Customer with CustomerID). EF is trying to re-insert the same customer after my initial context.SaveChanges();

So, how do I stop EF from trying to add the same customer when using the same datacontext?

I have been going around in circles for hours and getting the same error

{"The INSERT statement conflicted with the FOREIGN KEY constraint \\"FK_Order_Customer\\". The conflict occurred in database \\"xxxxx\\", table \\"dbo.Customer\\", column 'CustomerID'

The customer is newly created along with the order and orderlines. But it works first time and I get the CustomerID back from EF. But when I add new order and orderlines after the inital context.savechanges(); I get the FK error

Thanks for taking the time.

The problem was I was just calling DataContext.SaveChanges() with adding the entities to the correct model. For example:

Customer.Order.Add(customerInfo);

Well it was my lack of understanding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM