我有两个使用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。
我的问题是:为什么有空? 我该怎么做才能改变这种行为?