title: Entity Framework Add User to Role
body: <p>I asked a question earlier which was <a href="https://stackoverflow.com/questions/26756022/entity-framework-and-roles/26756447#26756447">answered here</a></p>
  
  <p>Basically I have 2 classes that are needed:</p>
  
  <pre><code>public class User : IUser
  {
      public string Id { get; set; }
  
      // Stripped for brevity
  
      public IList&lt;Role&gt; Roles { get; set; }
  
      public User()
      {
          this.Id = Guid.NewGuid().ToString();
      }
  }
  
  public class Role : IRole
  {
      public string Id { get; set; }
      public string Name { get; set; }
  
      public Role()
      {
          this.Id = Guid.NewGuid().ToString();
      }
  }
  </code></pre>
  
  <p>In my <strong>DbContext</strong> I have this declaration:</p>
  
  <pre><code>modelBuilder.Entity&lt;User&gt;()
      .HasMany(m =&gt; m.Roles)
      .WithMany()
      .Map(m =&gt; { 
          m.MapLeftKey("UserId");
          m.MapRightKey("RoleId"); 
          m.ToTable("UserRoles"); 
      });
  </code></pre>
  
  <p>That all works perfectly. Now, I want to add a user to a specific role, so I created a service following my service / repository / unit of work design pattern like this:</p>
  
  <pre><code>public class UserRoleService : Service&lt;UserRole&gt;
  {
      public UserRoleService(IUnitOfWork unitOfWork)
          : base(unitOfWork)
      {
  
      }
  
      public async Task&lt;IList&lt;UserRole&gt;&gt; GetAllAsync(string userId, params string[] includes)
      {
          return await this.Repository.GetAll(includes).Where(m =&gt; m.UserId.Equals(userId, StringComparison.OrdinalIgnoreCase)).ToListAsync();
      }
  
      public async Task CreateAsync(UserRole model)
      {
          var isInRole = await IsInRole(model.UserId, model.RoleId);
  
          if (isInRole)
              throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.UserInRole, new object[] { model.RoleId }));
  
          this.Repository.Create(model);
      }
  
      public async Task RemoveAsync(UserRole model)
      {
          var isInRole = await IsInRole(model.UserId, model.RoleId);
  
          if (!isInRole)
              throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.UserNotInRole, new object[] { model.RoleId }));
  
          this.Repository.Remove(model);
      }
  
      public async Task&lt;bool&gt; IsInRole(string userId, string roleId)
      {
          if (string.IsNullOrEmpty(userId))
              throw new ArgumentNullException("userId");
  
          if (string.IsNullOrEmpty(userId))
              throw new ArgumentNullException("roleId");
  
          var roles = await this.GetAllAsync(userId);
          var match = roles.Where(m =&gt; m.RoleId.Equals(roleId, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
  
          return (match == null);
      }
  }
  </code></pre>
  
  <p>The inherited service class looks like this:</p>
  
  <pre><code>public class Service&lt;T&gt; where T : class
  {
      private readonly IRepository&lt;T&gt; repository;
  
      protected IRepository&lt;T&gt; Repository
      {
          get { return this.repository; }
      }
  
      public Service(IUnitOfWork unitOfWork)
      {
          if (unitOfWork == null)
              throw new ArgumentNullException("unitOfWork");
  
          this.repository = unitOfWork.GetRepository&lt;T&gt;();
      }
  }
  </code></pre>
  
  <p>Now, because my <strong>DbContext</strong> doesn't have a <strong>DbSet</strong> for <strong>UserRoles</strong> it complains, so I added one. Then I got a complaint that the new table does not have a primary key set up, so I added one. So now my <strong>DbContext</strong> looks like this:</p>
  
  <pre><code>public class DatabaseContext : DbContext
  {
      // Removed for brevity
      public DbSet&lt;Role&gt; Roles { get; set; }
      public DbSet&lt;User&gt; Users { get; set; }
      public DbSet&lt;UserRole&gt; UserRoles { get; set; }
  
      static DatabaseContext()
      {
          //Database.SetInitializer&lt;IdentityContext&gt;(null); // Exsting database, do nothing (Comment out to create database)
      }
  
      public DatabaseContext()
          : base("DefaultConnection")
      {
          base.Configuration.LazyLoadingEnabled = false; // Disable Lazy Loading
      }
  
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          modelBuilder.Conventions.Remove&lt;OneToManyCascadeDeleteConvention&gt;(); // Remove Cascading Delete
  
          // Removed from brevity
          modelBuilder.Entity&lt;UserRole&gt;().HasKey(m =&gt; new { m.UserId, m.RoleId });
          modelBuilder.Entity&lt;User&gt;()
              .HasMany(m =&gt; m.Roles)
              .WithMany()
              .Map(m =&gt; { 
                  m.MapLeftKey("UserId");
                  m.MapRightKey("RoleId"); 
                  m.ToTable("UserRoles"); 
              });
      }
  }
  </code></pre>
  
  <p>The problem I have now, is that my code creates two tables for <strong>UserRole</strong> called <strong>UserRoles</strong> and <strong>UserRoles1</strong>.
  Can someone tell me how to get it to only use one table?</p>