EF repository pattern many to many insert

一曲冷凌霜 提交于 2019-12-03 20:24:36

I think you are having this problem because you are using the Repository pattern without the Unit Of Work pattern. Your ConcreteDAO<T> (= generic repository for entity type T, I guess) should not create a context (=unit of work). Instead your consuming method should create it explicitly and inject it into all repositories you need. You last method would then look like this:

public static void InsertAgent(int authorityID, int agentID)
{
    using (var unitOfWork = new UnitOfWork()) // unit of work = context
    {
        var daoAuthority = new ConcreteDAO<Authority>(unitOfWork);
        var daoAgent = new ConcreteDAO<Agent>(unitOfWork);

        var authority = daoAuthority.Single(p => p.ID.Equals(authorityID));
        var agent = daoAgent.Single(p => p.ID == agentID);

        authority.Agents.Add(agent);

        unitOfWork.SaveChanges();
    }
}

In many situations where changing relationships are involved you need more than one generic repository, but all work has to be done within the same context.

You can, btw, save to load the entities from the database because you know the primary key properties and don't want to change the entities themselves but only a relationship. In that case you can work with attached "stub" entities:

public static void InsertAgent(int authorityID, int agentID)
{
    using (var unitOfWork = new UnitOfWork())
    {
        var daoAuthority = new ConcreteDAO<Authority>(unitOfWork);
        var daoAgent = new ConcreteDAO<Agent>(unitOfWork);

        var authority = new Authority { ID = authorityID,
            Agents = new List<Agent>() };
        daoAuthority.Attach(authority);

        var agent = new Agent { ID = agentID };
        daoAgent.Attach(agent);

        authority.Agents.Add(agent);

        unitOfWork.SaveChanges();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!