实体框架代码优先和共享DataContext

时间:2012-03-13 03:16:49

标签: entity-framework-4.1 foreign-keys unit-of-work

我使用带有服务层工作模式的datacontext。这个服务层正在制作一些包含大量包含的GETS来检查现有数据。然后我在最后用一个工作单元提交插入。我一直收到这个错误:

  

操作失败:无法更改关系,因为一个或多个外键属性不可为空。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。

如果我减少了包含并将呼叫保持在单独的datacontext中,则插入有效。我的插入和外键是否正在发生什么?

public void Save(int memberId, int? divisionId, DivisionGymCourtModel model)
{
   ValidationProvider.Validate(model);

    var item = new DivisionGymCourt();

    if (model.Id > 0)
    {
        Expression<Func<DivisionGymCourt, object>> memberDivisionInclude = q => q.Division.Event.Members;

        item = _divisionGymCourtRepository.Get(new[] { memberDivisionInclude }, q => q.Id == model.Id);

        if (item == null)
            throw new ValidationException(new NotFound("Division gym not found"));

        item.Division.ValidatePermission(memberId);

        if (model.GymCourt.Id != item.GymCourtId)
            IsGymCourtInUse(memberId, item.DivisionId, model.GymCourt.Id);
    }
    else
    {
        IsGymCourtInUse(memberId, divisionId.Value, model.GymCourt.Id);

       // _divisionsService.GetById(memberId, divisionId.Value); <!-- this was removed while the below division check was used.  This call had some INCLUDES.

        var division = _divisionsRepository.Get(null, q => q.Event.Members.Any(m => m.MemberId == memberId) && q.Id == divisionId.Value);

        if(division == null)
            throw new ValidationException(new NotFound("Division not found"));

        item.DivisionId = divisionId.Value;
    }

    item.GymCourtId = model.GymCourt.Id;
    item.Order = model.Order;

    if (model.Id > 0)
        _divisionGymCourtRepository.Update(item);
    else
    {
        _divisionGymCourtRepository.Add(item); 
    }

    UnitOfWork.Commit(); // <---- Erroring

    model.Id = item.Id;
}

0 个答案:

没有答案