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