Why does removing an object from the EntityFramework DbContext set the navigation property to null?

I have two classes mapped to db tables with EF:

public class Relation
{
    // some properties

    public Address MainAddress { get; set; }
}

public class Address
{
    // some properties
}

      

In the method, I do the following:

    public Relation AddRelation(Relation relation)
    {
        var dbRelation = this.DbContext.Set<Relation>().Create();
        dbRelation.MainAddress = this.DbContext.Set<Address>().Create();

        // this one copies properties from one instance to another
        this.Copy(relation, dbRelation); 

        dbRelation.Id = Guid.NewGuid();
        dbRelation.MainAddress.Id = Guid.NewGuid();
        dbRelation.MainAddress.RelationId = dbRelation.Id;

        this.Add(dbRelation);

        this.Context.SaveChanges();

        // before detaching dbRelation.MainAddress != null
         this.Context.Entry<Relation>(dbRelation).State = EntityState.Detached;

        // afterwards dbRelation.MainAddress == null

        return dbRelation;
    }

      

I want to use dbRelation separately from context. But dbRelation.MainAddress gets a null assigned after the detach is done.

My question is why null? What should I do to change this behavior?

+3


source to share





All Articles