Note that there are some explanatory texts on larger screens.

plurals
  1. POEF repository pattern many to many insert
    text
    copied!<p>We have 2 tables:</p> <p>Table Authority:</p> <pre><code>public class Authority { public int ID {get;set;} public string Name{get;set;} ... } </code></pre> <p>Table Agents</p> <pre><code>public class Agent { public int ID{get;set;} public int FirstName{get;set;} } </code></pre> <p>And we have a relationship many-to-many between these two tables:</p> <pre><code>public class AuthorityConfiguration : EntityTypeConfiguration&lt;Authority&gt; { public AuthorityConfiguration() : base() { HasKey(p =&gt; p.ID); HasMany(p =&gt; p.Agents).WithMany(a =&gt; a.Authorities).Map(mc =&gt; { mc.MapLeftKey("AuthorityID"); mc.MapRightKey("AgentID"); mc.ToTable("AuthorityAgent"); }); ToTable("Authority"); } } </code></pre> <p>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.</p> <p>Problem 1: How can I get the Agent if my DAO is receiving an Authority?</p> <p>AuthorityDAO.cs</p> <pre><code>public static void InsertAgent(int authorityID, int agentID) { var dao = new ConcreteDAO&lt;Authority&gt;(); Authority authority = dao.Single(p =&gt; p.ID.Equals(authorityID)); // I can't do that because the relationship doesn't exist yet. var agent = authority.Agents.Where(p =&gt; p.ID.Equals(agentID)); authority.Agents.Add(agent); dao.Attach(authority); dao.SaveChanges(); } </code></pre> <p>I know I can create my context in the DAO to do it, but I will brake the Pattern, won't I?</p> <p>How can I do the method above?</p> <p>Thank you.</p> <p>EDIT: I found a solution but I don't know if it's the better way to do it:</p> <p>I created a constructor to my ConcreteDAO passing the ObjectContext and a method to get my object context:</p> <p>GenericDAO.cs</p> <pre><code>public ObjectContext GetContext() { return _context; } </code></pre> <p>ConcreteDAO.cs</p> <pre><code>public ConcreteDAO() { } public ConcreteDAO(ObjectContext context) : base(context) { } </code></pre> <p>And Inside my AuthorityDAO.cs</p> <pre><code> public static void InsertAgent(int authorityID, int agentID) { var dao = new ConcreteDAO&lt;Authority&gt;(); Authority authority = dao.Single(p =&gt; p.ID.Equals(authorityID)); dao.Attach(authority); var daoAgent = new ConcreteDAO&lt;Agent&gt;(dao.GetContext()); var agent = daoAgent.Single(p =&gt; p.ID == agentID); authority.Agents.Add(agent); dao.SaveChanges(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload