开发者

Entity Framework Insert Child Entities

开发者 https://www.devze.com 2023-01-19 19:41 出处:网络
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?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号