简体   繁体   中英

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?

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).

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