Quantcast
Channel: West Wind Message Board Messages
Viewing all articles
Browse latest Browse all 10393

Re: Help with NewEntity in EFCodeFirst wrapper

$
0
0
Re: Help with NewEntity in EFCodeFirst wrapper
West Wind Web Toolkit for ASP.NET
Re: Help with NewEntity in EFCodeFirst wrapper
Dec. 27, 2012
02:39 pm
3OE0VF8U7Show this entire thread in new window
Gratar Image based on email address
From:Rick Strahl
To:Matt Slay
Are you mapping the PK with AutoMapper? If so then yes that would fail.

I don't really understand why you're doing things quite this way. If you have a new Entity you need to create just create a new entity and map the values from the View or DTO or whatever you're mapping from. If you have an existing entity, load the original entity then map to the existing entity in the same way.

Whatever you do with a new entity, don't manually assign the PK to an existing PK or rightfully the insert will fail.

+++ Rick ---



Hi Rick - I'm trying to learn house to make use of NewEntity() in the EF Code First wrapper.... The case I am studying is a common task for may app, where I copy one Quote to a new Quote and edit it from there.

So, I'm using one BO to fetch the existing quote, then I create a new BO instance and use NewEntity(), then I map the existing Quote property values to new Quote entity, and call BO.Save().

However, it is giving an error because it is trying to create a new Customer record also, but it already exists in the table, so it should not be created again.

Here is the code:

public ActionResult test3() { var existingQuoteBO = new busQuote(9001); // Loads existing Quote# 9001 var newQuoteBO = new busQuote(); quote newQuote = newQuoteBO.NewEntity(); AutoMapper.Mapper.Map(existingQuoteBO.Entity, newQuote); // Copy existing values to newly created Quote newQuote.LineItems = new List<quoteitem>(); // Blank out the QuoteLineItems collection that was copied over newQuoteBO.Save(); <---See error message below.return RedirectToAction("edit", "quotes", new { id = newQuote.id }); }

Here is the error I am getting after calling Save():

Error: Violation of PRIMARY KEY constraint 'PK_customers_1'. Cannot insert duplicate key inobject'dbo.customers'. The statement has been terminated.} Westwind.BusinessFramework.EfCodeFirst.EfCodeFirstBusinessBase<MVC4_App1_EFData.Models.quote,MVC4_App1_EFData.QuoteContext> {MVC4_App1_EFData.busQuote}

Surely the EF thing is smart enough not to create a new Customer.???


So, if I skip the NewEntity() technique, and use this approach instead:

var newQuote = new quote();


Then copy the properties from the existing Quote to this new Quote (again using AutoMapper), then I call:

newQuoteBO.Context.Quotes.Add(newQuote); newQuoteBO.Save()

then it works just fine!!!


So, clearly there is something about using NewEntity() that I am missing.



Rick Strahl
West Wind Technologies


from Maui, Hawaii

Making waves on the Web


Viewing all articles
Browse latest Browse all 10393

Trending Articles