title: Represent View Without Key in Entity Framework
body: <p>I'm using a model produced with Devart Entity Developer (.edml file, which I understand is mostly similar to .edmx) to generate Entity classes whose relations are initialized in a DbContext class.  The database schema specifies no PK for View1, and all columns are nullable.  But the code generation assumes that for views lacking a primary key, all columns are the key. I.e., the .ssdl has all columns under the Key element and the DbContext has .IsRequired() specified on all, like so:</p>
  
  <p>ssdl excerpt:</p>
  
  <pre><code>...
  &lt;EntityType Name="View1"&gt;
    &lt;Key&gt;
      &lt;PropertyRef Name="FirstCol" /&gt;
      &lt;PropertyRef Name="Col2" /&gt;
      &lt;PropertyRef Name="LastCol" /&gt;
    &lt;/Key&gt;
    &lt;Property Name="FirstCol" Type="VARCHAR2" Nullable="false" MaxLength="4000" /&gt;
    &lt;Property Name="Col2" Type="VARCHAR2" Nullable="false" MaxLength="120" /&gt;
    &lt;Property Name="LastCol" Type="VARCHAR2" Nullable="false" MaxLength="20" /&gt;
  &lt;/EntityType&gt;
  ....
  </code></pre>
  
  <p>From DbContext:</p>
  
  <pre><code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {     
    #region View1
    modelBuilder.Entity&lt;View1&gt;()
      .HasKey(p =&gt; new { p.FirstCol, p.Col2, p.LastCol})
        .ToTable("View1", "Owner");
          // Properties:
          modelBuilder.Entity&lt;View1&gt;()
            .Property(p =&gt; p.FirstCol)
              .HasColumnName("FirstCol")
              .IsRequired()
              .HasMaxLength(4000)
              .HasColumnType("VARCHAR2");
          modelBuilder.Entity&lt;View1&gt;()
            .Property(p =&gt; p.Col2)
              .HasColumnName("Col2")
              .IsRequired()
              .HasMaxLength(120)
              .HasColumnType("VARCHAR2");
          modelBuilder.Entity&lt;View1&gt;()
            .Property(p =&gt; p.LastCol)
              .IsRequired()
              .HasMaxLength(20)
              .HasColumnType("VARCHAR2");
  </code></pre>
  
  <p>This causes a NullReferenceException when querying would return a row with one of the PK columns having null value.</p>
  
  <p>Is there a way to represent a view in EF without specifying keys or altering the database schema?  I've found this: <a href="http://elegantcode.com/2012/03/15/querying-entityframework-views-without-a-key/" rel="nofollow">http://elegantcode.com/2012/03/15/querying-entityframework-views-without-a-key/</a> </p>
  
  <p>Is this the preferred solution?  I suppose I could use DefiningQuery as well, but this seems to duplicate the sql that was used to generate the view?</p>