property type is not a valid key type in DBContext

c# entity-framework entity-framework-6

Question

When a WebAPI controller attempts to get data from the repository, I see this runtime error (Figure 1). A class that was inherited from DbContext was inserted by the repository's constructor (Figure 2). The view (Figure 4) in the SQL Server is where the POCO class (Figure 3) is defined. The table key is also supplied in the OnModelCreating() function. Why does the problem persist? Thanks.

Picture 1

System.InvalidOperationException occurred
  HResult=0x80131509
  Message=The property 'ConsultSID' cannot be used as 
  a key property on the entity 'ConsultTB' because the 
  property type is not a valid key type. Only scalar types, 
  string and byte[] are supported key types.

Picture 2

namespace myOrg.Repository {
  public class MyDb: DbContext {
    public MyDb(): base("name=MyConnectionString") {}

    public virtual DbSet < ConsultTB > ConsultTBs {
      get;
      set;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
      modelBuilder.Entity < ConsultTB > ().ToTable("vConsultTB", "App");

      modelBuilder.Entity<ConsultTB>().HasKey(c => c.ConsultSID);
    }
  }
}

Picture 3

namespace myOrg.Data {
  public class ConsultTB {
    //[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    //[Column("ConsultSID")]
    public long ConsultSID {
      get;
    }
    public int ServiceId {
      get;
    }
    public string ServiceName {
      get;
    }
    public short Sta3n {
      get;
    }
    public string StationName {
      get;
    }
    public DateTime RequestDate {
      get;
    }
  }
}

Picture 4

ALTER VIEW[App].[vConsultTB]
AS
SELECT
  ISNULL(A.[ConsultSID], -1) ConsultSID, A.[Sta3n], A.[PatientSID], A.[StationName],
  A.[RequestDate],
  p.patientIEN, p.PatientName, p.PatientLastName, p.PatientFirstName, p.PatientSSN, p.StreetAddress1, p.StreetAddress2, p.StreetAddress3
FROM[schema1].[ConsultTB_Consults] A
inner join[dbserver2].[schema2].[SPatient] P
on a.patientSID = p.patientSID and a.sta3n = p.sta3n
1
1
9/18/2017 6:32:36 PM

Accepted Answer

Your properties are getter-only, which means that function Object() { [native code] } options is the only person who can set them. However, EF has no issues with private setters, so you are free to use them.

    public long ConsultSID { get; private set; }

... etc.

The phrase "the property type is not a valid key type" in the error message in this case should have been more direct.

6
9/18/2017 7:11:26 PM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow