title: Entity Framework and roles
body: <p>I have an problem. I have a <strong>User</strong> which can have many <strong>Roles</strong>, but the <strong>Roles</strong> are global, so I have set up a table structure as follows:</p>
  
  <pre><code>CREATE TABLE [dbo].[Users](
      [Id] [nvarchar](128) NOT NULL,
      [UserName] [nvarchar](max) NULL,
      [Email] [nvarchar](max) NULL,
      [DateCreated] [datetime] NOT NULL,
      [DateModified] [datetime] NULL,
      [LastLoginDate] [datetime] NOT NULL,
      [PasswordHash] [nvarchar](max) NULL,
  CONSTRAINT [PK_dbo.Users] PRIMARY KEY CLUSTERED 
  
  CREATE TABLE [dbo].[UserRoles](
      [UserId] [nvarchar](128) NOT NULL,
      [RoleId] [nvarchar](128) NOT NULL,
   CONSTRAINT [PK_dbo.UserRoles] PRIMARY KEY CLUSTERED 
  (
      [UserId] ASC,
      [RoleId] ASC
  )
  
  CREATE TABLE [dbo].[Roles](
      [Id] [nvarchar](128) NOT NULL,
      [Name] [nvarchar](max) NULL,
  CONSTRAINT [PK_dbo.Roles] PRIMARY KEY CLUSTERED 
  (
      [Id] ASC
  )
  </code></pre>
  
  <p>The <strong>UserRoles</strong> table has foriegn keys set up for both the <strong>Roles</strong> and <strong>Users</strong> table on the respective <strong>Id</strong> columns.</p>
  
  <p>In my code, I have this:</p>
  
  <pre><code>public class User : IUser
  {
      public string Id { get; set; }
  
      // Stripped for brevity
  
      public IList&lt;UserRole&gt; Roles { get; set; }
  
      public User()
      {
          this.Id = Guid.NewGuid().ToString();
      }
  }
  
  public class UserRole
  {
      public string RoleId { get; set; }
      public string UserId { get; set; }
  }
  
  public class Role : IRole
  {
      public string Id { get; set; }
      public string Name { get; set; }
      public IList&lt;UserRole&gt; Users { get; set; }
  
      public Role()
      {
          this.Id = Guid.NewGuid().ToString();
      }
  }
  </code></pre>
  
  <p><strong>EntityFramework</strong> is fine with this class and with my mapping as follows:</p>
  
  <pre><code>modelBuilder.Entity&lt;UserRole&gt;().HasKey(m =&gt; new { m.UserId, m.RoleId });
  </code></pre>
  
  <p>Everything for the mapping works.
  Now what I would really like, is for the <strong>User</strong> class to have a list of <strong>Roles</strong> and not <strong>UserRoles</strong>.</p>
  
  <p>So, I would like it to look like this:</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();
      }
  }
  </code></pre>
  
  <p>I am sure you can see the problem here.
  Can someone think of a solution where my table structure stays the same, but I can access the <strong>Roles</strong> instead of the <strong>UserRoles</strong>?</p>
  
  <p>Sorry if my explanation is not good.</p>