Özgür Kaplan
Özgür Kaplan

Reputation: 2136

Creating and Inserting new entity from Existing One in Linq To Sql

I have 2 tables; PriceList and PriceListDetail with one to many realitonship. After inserting a new PriceList and I need to copy PriceListDetail's of an existing PriceList.

var pricedetails= db.PriceListDetails.Where(p => p.PriceList Id == SomeExistingPriceListID);

All I need is to change priceListID of pricedetails above and Insert them to PriceListDetail table. When I modify priceListId of pricedetails and try to insert them I get 'cannot insert entities that already exists'.

Obvious solution is to create new entities and copy values one by one from pricedetails then insert.

Is there a way to avoid one by one copying? Maybe create duplicate rows then modify duplicated ones?

Upvotes: 1

Views: 763

Answers (1)

Boomer
Boomer

Reputation: 1478

Entity frameworks uses another key than your primary key, and it is called an entity key. So having your PriceListDetails, all you have to do is to change the primary key ID and set the entity key to NULL (NULL means a new row).

Upvotes: 1

Related Questions