DbContextScope icon indicating copy to clipboard operation
DbContextScope copied to clipboard

While saving an object with navigation properties, the dbcontext saves two elements of same object

Open theMost1ted opened this issue 10 years ago • 1 comments

Imagine we have an entity Client and an entity Vehicle we have Client.vehicle = Vehicle; if we try to save the object Client, it will be saved as two elements in the database!

theMost1ted avatar Aug 21 '15 16:08 theMost1ted

This is not an issue with this library but a misunderstanding from your side of how Entity Framework/ORMs work.

Because of its state management capabilities, when Entity Framework works with graphs, its entity state behavior doesn’t always align with your ideas of how it should work. https://msdn.microsoft.com/en-us/magazine/dn166926.aspx

You probably have two options to rectify this mistake:

Option 1. Change your Client domain class

Add the following property:

[Column("Name of the VehicleID column on your CLient table here") public int Vehicle_Id {get;set;}

In your code where you set Client.vehicle = Vehicle;

Change it to Client.Vehicle_id = Vehicle.Id;

Option 2. Attach the entity within your dbContextScope:

public void Save(Client client, Vehicle vehicle)
{
    using (var dbContextScope = _dbContextScopeFactory.Create())
    {
        //code that adds your Client to the context e.g.
        _clientRepository.Save(client);

        //Part you are interested in
        dbContextScope.DbContexts.Get<NameOfYourContext>().Vehicles.Attach(vehicle);
        dbContextScope.SaveChanges();
    }
}

Seany84 avatar Feb 06 '16 00:02 Seany84