Note that there are some explanatory texts on larger screens.

plurals
  1. PORepresent View Without Key in Entity Framework
    primarykey
    data
    text
    <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>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload