简体   繁体   中英

Can't add a record twice with Linq to SQL

In the legacy system I look after I have to add the same record to a table, twice.

There is an identity on the table that increments with each new record.

If I do the following I get the error: "Cannot add an entity that already exists"

Is there a way to add a record twice without creating another PricingSnapshot object?

            PricingSnapshot pricingSnapshot = new PricingSnapshot
            {
                InvoiceOrderLineId = invoiceOrderLineId,
                GrossPaymentValue = grossTotal,
                CreatedBy = "Pricing Engine",
                CreatedDate = DateTime.Now
            };
            dBpostChanges.PricingSnapshots.InsertOnSubmit(pricingSnapshot);
            dBpostChanges.SubmitChanges();

        dBpostChanges.PricingSnapshots.InsertOnSubmit(pricingSnapshot);
            dBpostChanges.SubmitChanges();

Creating another Pricing Snapshot object is the "correct" way to do it. It's the way Linq to SQL was designed, so doing anything else would be swimming against the current.

You will have to create a new PricingSnapshot object since after you submit changes the first time, your object pricingSnapshot still exists and now has been assigned an ID from your table. So if you were to try to access the ID of the object after the first submit, you will find it has one, therefore adding it to the table again, will be adding a duplicate.

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