property type is not a valid key type in DBContext

c# entity-framework entity-framework-6

Question

I am getting this runtime error (Figure 1) when a WebAPI controller tries to get data from the repository. The repository constructor injected a class (Figure 2) inherited from DbContext. The POCO class (Figure 3) is specified in the a DbSet points to the view (Figure 4) in the SQL Server. In the OnModelCreating() in the table key is also specified. Why the error still occurs? Thanks.

Figure 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.

Figure 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);
    }
  }
}

Figure 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;
    }
  }
}

Figure 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 they can only be set by constructor parameters. EF doesn't have any problems with private setters though, so you're free to use ...

    public long ConsultSID { get; private set; }

... etc.

The error message "the property type is not a valid key type" could have been a bit more to the point here.

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

Popular Answer

Properties in EF models must be writable.

You need to add set; accessors.



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