I am trying to persist the collection of child elements, the solution works but I would like to ask the more experienced people if the approac开发者_开发知识库h is the right one?
public bool InsertNewActionHistory(ActionHistory actionHistory)
{
bool result = false;
using (TransactionScope transactionScope = new TransactionScope())
{
this.ActionHistories.AddObject(actionHistory);
if (actionHistory is ActionUpdate)
{
foreach (ActionUpdateDetail updateDetail in ((ActionUpdate)actionHistory).ActionUpdateDetails)
{
ActionUpdateDetails.AddObject(updateDetail);
}
}
this.CommitChanges();
transactionScope.Complete();
result = true;
}
return result;
}
If ActionUpdateDetail
is related to ActionUpdate
via a navigation property, then you don't need 3/4 of the code. You could just do:
public bool InsertNewActionHistory(ActionHistory actionHistory)
{
this.ActionHistories.AddObject(actionHistory);
return true;
}
Navigation properties ensure that related objects are added together.
Note that this can be harder if you use POCO proxies or pure POCOs. Beginners with the EF should probably stick with DB-first or model-first until you learn the rules of the road.
精彩评论