Search code examples
c#entity-frameworkentity-framework-4automapperautomapping

Avoid not necessary insert subclass when insert with Entity Framework


I have this objects :

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string Street { get; set; }
    public Locality Locality { get; set; }
}

public class Locality
{
    public string City { get; set; }
    public string ZipCode { get; set; }
}

In the Entity Framework model, I have this PERSON, ADDRESS, LOCALITY

I'm doing this :

Mapper.CreateMap<Person, PERSON>();
Mapper.CreateMap<Address, ADDRESS>();
    .ForMember(x => x.Locality, opt => opt.Ignore())

When I try to insert a new Person in the database I see with the profiler (Entity Framework Profiler) an insert on Locality table too. I just want a insert a User that's it.

Any idea ?


Solution

  • You need to set the State on the Locality in the new Person to EntityState.Unchanged.

     context.ObjectStateManager
         .ChangeObjectState
         (newPerson.Locality, System.Data.EntityState.Unchanged);