0

这是使用 EF 向 sql server 添加新实体的简单代码

   var isNewEntity = entity.Id == 0;

        if (isNewEntity)
        {
            _unitOfWork.Context.DbTripReportDefinitionSectionSet.Add(entity);
        }
        else
        {
            ObjectStateEntry stateEntry;
            _unitOfWork.ObjectStateManager.TryGetObjectStateEntry(entity, out stateEntry);

            if (stateEntry == null)
            {
                _unitOfWork.Context.DbTripReportDefinitionSectionSet.Attach(entity);
            }

            _unitOfWork.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
        }

        _unitOfWork.Save();

        return entity.Id;

问题是我有一个例外

'ObjectStateManager 中已存在具有相同键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象。对于已经存在但未跟踪的实体。

所以_unitOfWork.ObjectStateManager.TryGetObjectStateEntry(entity, out stateEntry);返回 false 并且这段代码_unitOfWork.Context.DbTripReportDefinitionSectionSet.Attach(entity);抛出异常。我猜是因为已经附加了导航属性。如何在没有导航属性的情况下附加这些实体?或者我该如何以另一种方式解决这些问题?

4

1 回答 1

0

Without further information, I may advise you to create a new Context instance.

Most probably your assumption about navigation properties is right; but instead of trying to fix the code, it is better for you to create a new context unless there are operations which require to be committed in the same transaction (I am assuming you are employing unit of work pattern).

于 2013-02-06T12:46:24.467 回答