3

我有两个类使用 EF 映射到 db 表:

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 存在?我应该怎么做才能改变这种行为?

4

0 回答 0