Title: SaveChanges on Entity Framework 3.5 is saving Unchanged entities (duplicate them on database)
Tags: .net;entity-framework;savechanges
Question: I'm using .net 3.5 and Entity Framework 3.5 also (cannot upgrade to a recent version).
When I use EF to save a new entity on the database, all the entity references are duplicated even with state 'Unchanged' and an ID > 0.
Here is a little of the code:
public long Insert(CarDTO carDTO)
Car car = Mapper.Map<CarDTO, Car&gt;(carDTO);
using (var context = new Entities())
{
car.Wheel =
context
.Wheels
.FirstOrDefault(item =&gt; item.ID == carDTO.Wheel.ID);
context.AddToCar(car);
context.SaveChanges();
}
As you can see, I only create a new entity of type Car, but when the SaveChanges is executed, it also creates a new copy on the database of the referenced entity Wheel.
Can someone help me understanding why is this happening? As I said, entity Wheel has is state Unchanged and has an EntityID, so it should not be updated or worst duplicated on the database as it was a new entity.
Comment: use Sql Server Profiler to see what is really send to the database (and when). I also don't know what Mapper is and if it contributes to the problem - see how many entities you have in context before SaveChanges(). Another question is if you map your CUD operations to stored procedures and if so what happens there.

Here is the accepted answer: Found a solution for the problem!
For some reason, the mapping should not map reference entities. So the solution to avoid database replication of referenced entities should ignore mapping for this references like the example below:
public long Insert(CarDTO carDTO)
Map map = Mapper.CreateMap<CarDTO, Car&gt;();
map.ForMember(dto =&gt; dto.Wheel, entity =&gt; entity.Ignore());
Car car = Mapper.Map<CarDTO, Car&gt;(carDTO);
using (var context = new Entities())
{
car.Wheel =
context
.Wheels
.FirstOrDefault(item =&gt; item.ID == carDTO.Wheel.ID);
context.AddToCar(car);
context.SaveChanges();
Remember that you cannot create the mapping elsewhere (previous the call of this method) or it will use the configuration of that previous declaration and do not have the ignore statement.
The mapper I was using is this one: https://github.com/AutoMapper/AutoMapper


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2013:00:03/11/13', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<.net><entity-framework><savechanges>', 'Title': 'SaveChanges on Entity Framework 3.5 is saving Unchanged entities (duplicate them on database)', 'ViewCount': 574, 'id': 15337475, 'user_AboutMe': '<p>Software Developer</p>\n', 'user_AccountId': 1427910.0, 'user_DisplayName': 'Benjamim', 'user_Reputation': 502.0, 'user_Views': 19.0, 'user_id': 1350979.0}}