ado net Entity framework 自关联的数据无法保存
我有一个实体类 房屋, 房屋这个实体自关联,分别为父房屋和子房屋. 现在有两个实体parentHouse和childHouse,已经都存在数据库里了,我想把二者关联起来.但保存.报错的代码是"The EntityReference could not be loaded because it is not attached to an ObjectContext". 下面是代码
public Boolean 保存房屋间关系(房屋 parentHouse, 房屋 childHouse, String 关系类型)
{
int i = 0;
using (CHILIEntities context = new CHILIEntities())
{
context.Connection.Open();
DbTransaction trans = context.Connection.BeginTransaction();
try
{
//保存房屋
EntityKey key;
object originalHouse;
key = context.CreateEntityKey("房屋", childHouse);
if (context.TryGetObjectByKey(key, out originalHouse))
{
context.Attach(parentHouse);
childHouse.父房屋编号 = parentHouse.房屋编号;
//if (!childHouse.房屋1.IsLoaded)
//{
// childHouse.房屋1.Load();
//}
//childHouse.房屋1.Add(parentHouse);
//childHouse.房屋2.EntityKey = context.CreateEntityKey("房屋", parentHouse);
if (!childHouse.房屋2Reference.IsLoaded)
{
childHouse.房屋2Reference.Load();
}
childHouse.房屋2 = parentHouse;
context.ApplyCurrentValues<房屋>(key.EntitySetName, childHouse);
i = context.SaveChanges();
trans.Commit();
}
else
{
throw new PLATOException("没有对应的房屋");
}
return true;
}
catch (Exception e)
{
Console.WriteLine("exception:" + e.StackTrace);
throw e;
}
finally
{
context.Connection.Close();
}
}
}