EF repository pattern many to many insert

ε祈祈猫儿з 提交于 2019-12-05 02:59:19

问题


We have 2 tables:

Table Authority:

public class Authority
{
   public int ID {get;set;}
   public string Name{get;set;}
      ...
}

Table Agents

public class Agent
{
  public int ID{get;set;}
  public int FirstName{get;set;}
}

And we have a relationship many-to-many between these two tables:

public class AuthorityConfiguration : EntityTypeConfiguration<Authority>
{
    public AuthorityConfiguration()
        : base()
    {
        HasKey(p => p.ID);

        HasMany(p => p.Agents).WithMany(a => a.Authorities).Map(mc =>
            {
                mc.MapLeftKey("AuthorityID");
                mc.MapRightKey("AgentID");
                mc.ToTable("AuthorityAgent");
            });


        ToTable("Authority");

    }
}

Everything is working fine. But now I have a page to create an association between the tables and I need to insert into my table "authorityAgent" the relationship using Repository Pattern.

Problem 1: How can I get the Agent if my DAO is receiving an Authority?

AuthorityDAO.cs

public static void InsertAgent(int authorityID, int agentID)
    {
        var dao = new ConcreteDAO<Authority>();

        Authority authority = dao.Single(p => p.ID.Equals(authorityID));

        // I can't do that because the relationship doesn't exist yet.
        var agent = authority.Agents.Where(p => p.ID.Equals(agentID));


        authority.Agents.Add(agent);

        dao.Attach(authority);

        dao.SaveChanges();

    }

I know I can create my context in the DAO to do it, but I will brake the Pattern, won't I?

How can I do the method above?

Thank you.

EDIT: I found a solution but I don't know if it's the better way to do it:

I created a constructor to my ConcreteDAO passing the ObjectContext and a method to get my object context:

GenericDAO.cs

public ObjectContext GetContext()
{
     return _context;
}

ConcreteDAO.cs

public ConcreteDAO()
{

}

public ConcreteDAO(ObjectContext context)
    : base(context)
{
}

And Inside my AuthorityDAO.cs

 public static void InsertAgent(int authorityID, int agentID)
 {
     var dao = new ConcreteDAO<Authority>();
     Authority authority = dao.Single(p => p.ID.Equals(authorityID));
     dao.Attach(authority);

     var daoAgent = new ConcreteDAO<Agent>(dao.GetContext());

     var agent = daoAgent.Single(p => p.ID == agentID);

     authority.Agents.Add(agent);

     dao.SaveChanges();
}

回答1:


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();
    }
}


来源:https://stackoverflow.com/questions/8576916/ef-repository-pattern-many-to-many-insert

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