title: Mapping Database Views to EF 5.0 Code First w/Migrations
body: <p>I'm trying to map a SQL View to an entity in EF 5.0 Code First w/Migrations for displaying some basic information on a page without having to query multiple tables for that information (which currently takes ~20 seconds to load. <strong>NOT GOOD.</strong>). I've heard that it is possible to do, but I haven't been able to figure out or find online a way to properly do so.</p>
  
  <p>EDIT: For a more in-depth look at my solution to this problem, read <a href="http://www.paragon-inc.com/resources/blogs-posts/a-certain-point-of-view-part-1-ef-code-first" rel="noreferrer">this blog post</a> on the subject.</p>
  
  <p>Here is my View:</p>
  
  <pre><code>CREATE VIEW [dbo].[ClientStatistics]
  AS
  SELECT       ROW_NUMBER() OVER (Order By c.ID) as Row, c.LegacyID, c.ID, c.ClientName, slc.AccountManager, slc.Network,
                               (SELECT        MAX(CreatedDate) AS Expr1
                                 FROM            dbo.DataPeriods
                                 WHERE        (ClientID = c.ID)) AS LastDataReceived,
                               (SELECT        MAX(ApprovedDate) AS Expr1
                                 FROM            dbo.DataPeriods AS DataPeriods_2
                                 WHERE        (ClientID = c.ID)) AS LastApproved,
                               (SELECT        MAX(ReportProcessedDate) AS Expr1
                                 FROM            dbo.DataPeriods AS DataPeriods_1
                                 WHERE        (ClientID = c.ID)) AS LastReportProcesssed
  FROM            dbo.Clients AS c INNER JOIN
                           dbo.SLClients AS slc ON c.ID = slc.ClientID
  </code></pre>
  
  <p>Here is the entity:</p>
  
  <pre><code>public class ClientStatisticsView
  {
      [Key]
      public int Row { get; set; }
      public int LegacyID { get; set; }
      public int ClientID { get; set; }
      public string ClientName { get; set; }
      public string AccountManager { get; set; }
      public string Network { get; set; }
      public DateTime LastDataReceived { get; set; }
      public DateTime LastApproved { get; set; }
      public DateTime LastReportProcessed { get; set; }
  }
  </code></pre>
  
  <p>And finally my mapping in <code>DbContext</code>:</p>
  
  <pre><code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
      modelBuilder.Conventions.Remove&lt;OneToManyCascadeDeleteConvention&gt;();
  
      modelBuilder.Entity&lt;ClientStatisticsView&gt;().ToTable("ClientStatistics");
  
      base.OnModelCreating(modelBuilder);
  }
  </code></pre>
  
  <p>All of this gives me the following error:</p>
  
  <p><code>There is already an object named 'ClientStatistics' in the database.</code></p>
  
  <p>What am I doing wrong? Is there any way to me to accomplish this, or should I be doing something else instead?</p>