我把主从表分别写成两个类A和B,其中B类作为A类的明细集合属性,如:public List<B> Details
{
get { return m_detail; }
set { m_detail = value; }
}现在新增时没问题,但更新时,明细中既有新增又有删除又有更新,该怎么处理?
{
get { return m_detail; }
set { m_detail = value; }
}现在新增时没问题,但更新时,明细中既有新增又有删除又有更新,该怎么处理?
调试欢乐多
*****************************************************************************
欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码) http://feiyun0112.cnblogs.com/
public override int Update(A entity)
{
try
{
this.BeginTransaction(); // 取得数据库里面的版本
ExportPlanEntity oldObject = this.GetObjectByID(entity.ID); // 更新主表
int result = this.Update(entity, true); // 插入失败回滚并返回
if (result == DB_Faild)
{
return DB_Faild;
} // 更新明细
foreach (B detail in entity.Details)
{
// 如果当前的ID为空,则为新增明细
if (detail.ID == 0)
{
//外键关联
detail.ParentID = entity.ID;
result = this.Insert(detail, true);
}
else
{
// 除去ID为0的情况,其他就是需要更新的
result = this.Update(detail, true);
} // 更新失败回滚并返回
if (result == DB_Faild)
{
this.RollBackTransaction();
return DB_Faild;
}
} // 把界面上被删除的明细找出来删除之
bool isFinded = false;
foreach (B oldDetail in oldObject.Details)
{
isFinded = false;
foreach (B newDetail in entity.Details)
{
if (newDetail.ID == oldDetail.ID)
{
isFinded = true;
}
}
if (!isFinded)
{
this.Delete(oldDetail, true);
}
} this.CommitTransaction();
return Success;
}
catch (Exception err)
{
this.RollBackTransaction();
Exception errInfo = new Exception("执行更新语句时发现以下错误:\r\n" + err.Message, err);
m_errofInfo.Clear();
m_errofInfo.Add("Update", errInfo.Message);
return DB_Faild;
}
}
我的主从表id都是数据库自动生成的。
对于子类B
新增:B类中的主关键字段值设为空,其他要保存到数据库中的字段有值;
更新:B类中的主关键字段和其他需要保存到数据库中的字段都有值。
删除:只有B类中的主关键字段有值,其他字段都没有值。
这样就能分开了
那还得再学习Nhibernate类库,不至于为了解决这个问题去该一套架构