title: EF Code First Multiple entities to same table
body: <p>I am interested in how I can map two entities to same table, by using code first. Here's an example:</p>
  
  <pre><code>public class User
  {
      [Key]
      public int UserId { get; set; }
      public string Name { get; set; }
      public byte Age { get; set; }
      public bool Active { get; set; }
      public DateTime Created { get; set; }
  }
  
  public class UserViewModel
  {
      [Key]
      public int UserId { get; set; }
      public string Name { get; set; }
      public byte Age { get; set; }
  }
  </code></pre>
  
  <p>Basically I'm fed up with building repositories. I want to map all possible models for configuration portal, user portal, other services in modelbuilder and just use DbContext for everything. I want to set User class as top of the hierarchy and a class that builds the database, while all other models should just be there for various applications.</p>
  
  <p>I don't want to use automapper. I've also done fair amount of manual coding which just wasted my time, and every single modification requires me to go back to repository and recode - which annoys me.</p>
  
  <p>I've tried to use this in modelbuilder, but it warns me that hierarchy is not valid:</p>
  
  <pre><code>    protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          modelBuilder.Entity&lt;User&gt;().Map(p =&gt; { p.ToTable("Users"); });
          modelBuilder.Entity&lt;UserViewModel&gt;().Map(p =&gt; { p.ToTable("Users"); });
      }
  </code></pre>
  
  <p>Also keep in mind that I'm not trying to achieve "Table splitting". I don't want my table to be split in two entities, I want rather to have all columns nullable, except one with primary key, and allow different applications/web services/web portals to populate as much data as they've been granted access for.</p>
  
  <p>Thanks for all the tips :)</p>