我一直在四处寻找如何更新父实体的子代,但找不到符合我要求的东西。我正在使用数据网格视图控件将这些子数据绑定到我的表单和DataSet。我需要能够知道我的数据网格中的哪些行被修改,删除和添加,这就是我需要将其传递给DataSet的原因。
以下是我的父母和子女映射:
<class name="Fees" table="fees">
<id name="Id" column="id">
<generator class="guid" />
</id>
<property name="Code" column="code" />
<property name="Description" column="description" />
<property name="Status" column="status" />
<bag name="FeesDetails" table="fees_lines" inverse="true" cascade="all">
<key column="fees_id" />
<one-to-many class="FeesLines" />
</bag>
<class name="FeesLines" table="fees_lines">
<id name="Id" column="id">
<generator class="guid" />
</id>
<property name="FeesId" column="fees_id" type="System.Guid" insert="false" update="false" />
<property name="Description" column="description" />
<property name="Amount" column="amount" />
<many-to-one name="Fee" class="Fees" column="fees_id" />
我需要能够使用NHibernate更新我的子记录,那么你是如何做到的?
答案 0 :(得分:0)
我找到了一种方法来更新我的孩子记录,这是我如何做到的:
public bool UpdateFees(string id, string code, string desc, DataSet details)
{
bool success = false;
using (ITransaction transaction = Session.BeginTransaction())
{
try
{
Fees fees = (Fees)Session.Get("EnrollmentSystem.Domain.Fees", Guid.Parse(id));
fees.Code = code;
fees.Description = desc;
if (details.HasChanges())
{
if (details.HasChanges(DataRowState.Added))
{
DataSet tempDataSet = details.GetChanges(DataRowState.Added);
foreach (DataRow row in tempDataSet.Tables[0].Rows)
{
FeesLines lines = new FeesLines();
lines.Fee = fees;
lines.Id = Guid.NewGuid();
lines.Description = row["Description"].ToString();
lines.Amount = (row["Amount"].ToString() == "") ? 0 : Convert.ToDecimal(row["Amount"].ToString());
fees.FeesDetails.Add(lines);
Session.Save(lines);
}
}
if (details.HasChanges(DataRowState.Modified))
{
DataSet editedSet = details.GetChanges(DataRowState.Modified);
foreach (DataRow row in editedSet.Tables[0].Rows)
{
var item = (from f in fees.FeesDetails
where f.Id.Equals(Guid.Parse(row["Id"].ToString()))
select f).SingleOrDefault();
if (item != null)
{
item.Description = row["Description"].ToString();
item.Amount = Convert.ToDecimal(row["Amount"].ToString());
Session.SaveOrUpdate(item);
}
}
}
if (details.HasChanges(DataRowState.Deleted))
{
DataSet deleted = details.GetChanges(DataRowState.Deleted);
for (int row = 0; row < deleted.Tables[0].Rows.Count; row++ )
{
var item = (from f in fees.FeesDetails
where f.Id.Equals(Guid.Parse(deleted.Tables[0].Rows[row][0, DataRowVersion.Original].ToString()))
select f).SingleOrDefault();
if (item != null)
{
fees.FeesDetails.Remove(item);
}
}
}
}
Session.SaveOrUpdate(fees);
transaction.Commit();
success = transaction.WasCommitted;
}
catch (Exception ex)
{
transaction.Rollback();
throw;
}
}
return success;
}
我创建了一个函数,我传递了父数据的新值,并传递了包含新的/修改/删除的子集的DataSet。