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

Help with NewEntity in EFCodeFirst wrapper

$
0
0
Help with NewEntity in EFCodeFirst wrapper
West Wind Web Toolkit for ASP.NET
Help with NewEntity in EFCodeFirst wrapper
Dec. 27, 2012
01:54 pm
3OE0TSOW3Show this entire thread in new window
Gratar Image based on email address
From:Matt Slay
To:Rick Strahl
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.


Viewing all articles
Browse latest Browse all 10393

Trending Articles