为什么从EntityFramework DbContext中分离对象会将null设置为导航属性?

时间:2013-01-25 16:22:10

标签: entity-framework

我有两个使用EF编写数据库表的类:

public class Relation
{
    // some properties

    public Address MainAddress { get; set; }
}

public class Address
{
    // some properties
}

在方法中,我执行以下操作:

    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;
    }

我想使用与上下文分离的dbRelation。 但是dbRelation.MainAddress在执行Detach后得到一个null。

我的问题是:为什么有空? 我该怎么做才能改变这种行为?

0 个答案:

没有答案