gpt4 book ai didi

poco - 无法使用工作单元模式从 POCO 中删除子实体

转载 作者:行者123 更新时间:2023-12-02 04:10:41 25 4
gpt4 key购买 nike

我在 EF4 CTP5 项目上使用 POCO 类,但在删除子属性时遇到问题。这是我的例子(希望不会太长)。

旅游类相关部分

public partial class Tour
{
public Guid TourId { get; private set; }
protected virtual List<Agent> _agents { get; set; }

public void AddAgent(Agent agent)
{
_agents.Add(agent);
}

public void RemoveAgent(Guid agentId)
{
var a = Agents.Single(x => x.AgentId == agentId);
_agents.Remove(Agents.Single(x => x.AgentId == agentId));
}
}

命令处理程序
public class DeleteAgentCommandHandler : ICommandHandler<DeleteAgentCommand>
{
private readonly IRepository<Core.Domain.Tour> _repository;
private readonly IUnitOfWork _unitOfWork;

public DeleteAgentCommandHandler(
IRepository<Core.Domain.Tour> repository,
IUnitOfWork unitOfWork
)
{
_repository = repository;
_unitOfWork = unitOfWork;
}

public void Receive(DeleteAgentCommand command)
{
var tour = _repository.GetById(command.TourId);
tour.RemoveAgent(command.AgentId);

// The following line just ends up calling
// DbContext.SaveChanges(); on the current context.

_unitOfWork.Commit();
}
}

这是我在 UnitOfWork 调用 DbContext.SaveChanges() 时遇到的错误。

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.



发生这种情况是因为 EF 不会仅仅因为它已从我的 Tour 类的 Agents 集合中删除而自动从数据库中删除代理实体。

我需要明确调用 dbContext.Agents.DeleteObject(a); ,但我的问题是,我无法从我的 POCO 中访问 dbContext。

有没有办法处理这种情况?

最佳答案

以您当前的架构,恐怕您需要满足您的DeleteAgentCommandHandler使用第二个存储库(我猜是 IRepository<Core.Domain.Agent>),然后调用类似 Delete(command.AgentId) 的东西在第二个存储库上。

或者您可以扩展您的 IUnitOfWork成为存储库的工厂,因此接口(interface)将获得一个额外的方法,如 T CreateRepository<T>()它允许您从工作单元中提取通用存储库的任何实例。 (然后你只需要注入(inject) IUnitOfWorkDeleteAgentCommandHandler 中,而不是存储库了。)

或者远离业务/UI 层中的通用存储库。如果 Agent完全依赖 Tour它根本不需要存储库。非泛型 ITourRepository可以有方法来适本地处理从数据库层中的游览中删除代理的情况。

关于poco - 无法使用工作单元模式从 POCO 中删除子实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5344477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com