Modeling a many-to-many relationship between 3 tables with Code First
<p>I have the following 3 entities:</p>

<ul>
<li>User</li>
<li>Account</li>
<li>Role</li>
</ul>

<p>And the relationship goes like</p>

<ul>
<li>One user can have many accounts</li>
<li>One account can belong to many users</li>
<li>Each user has a role in an account</li>
<li>There are a few, predefined roles (defined in the enum Roles)</li>
</ul>

<p>I got this far:</p>

<pre><code>public class User
{
    public int Id { get; set; }
    public ICollection&lt;Account&gt; Accounts { get; set; }
}

public class Account
{
    public int Id { get; set; }
    public ICollection&lt;User&gt; Users { get; set; }
}

public class Role
{
    public int Id { get; set; }
    public string RoleName { get; set; }
    public virtual ICollection&lt;User&gt; Users { get; set; }
    public virtual ICollection&lt;Account&gt; Accounts { get; set; }
}
</code></pre>

<p>Every time an user registers, they also create an account, so I thought of this:</p>

<pre><code>public async Task AddAccountAsync(User user, string accountName)
{
    Account account = new Account(user, accountName);
    Role role = new Role(Roles.Owner);
    Accounts.Add(account);
    user.Accounts.Add(account);
    Entry(user).State = EntityState.Modified;
    await SaveChangesAsync();
 }
</code></pre>

<p>But I am not sure how to tie the role to the user to the account, so I can get the role an user has in an account. </p>

<p>For example:</p>

<p>Consider 3 users and 3 accounts:  </p>

<ul>
<li>Account1 = (User1, Owner), (User2, TeamMember)  </li>
<li>Account2 = (User2, Owner)  </li>
<li>Account3 = (User3, Owner), (User1, ReadOnlyMember)</li>
</ul>

<p>Following @IvanStoev's answer, I got this:</p>

<pre><code>public async Task AddAccountAsync(User user, string accountName)
{
   Role role = new Role(Roles.Owner);
   Account account = new Account(model.AccountCurrency, model.AccountName, model.Description);
   UserAccount uc = new UserAccount
   {
       User = user,
       Account = account,
       Role = role
   };
   account.UserAccounts.Add(uc);
   Accounts.Add(account);

   user.UserAccounts.Add(uc);
   Entry(user).State = EntityState.Modified;
   await SaveChangesAsync();
}
</code></pre>

<p>Should I be saving the UserAccount object (as a <code>DbContext&lt;UserAccount&gt;</code>)?</p>