"EntityType does not have a specific key" exception, although the key is determined using HasKey

Using EF 5 (reverse engineering code first), my model worked fine until it suddenly stopped.

\ tSystem.Data.Entity.Edm.EdmEntityType :: EntityType 'ProjectsDate' does not have a key. Define a key for this EntityType.

\ tSystem.Data.Entity.Edm.EdmEntityType :: EntityType 'ProjectsRisk' does not have a specific key. Define a key for this EntityType.

I define the key using a free API, not attributes, here are my ProjectsDates classes.

public partial class ProjectsDate { public string OSProjectCode { get; set; } public Nullable<System.DateTime> TargetStart { get; set; } public Nullable<System.DateTime> EndDateOriginal { get; set; } public Nullable<System.DateTime> EndDateChangeControl { get; set; } public Nullable<System.DateTime> EndDateActual { get; set; } public Nullable<System.DateTime> GoLiveAgreed { get; set; } public Nullable<System.DateTime> GoLiveActual { get; set; } public virtual Project Project { get; set; } } 
 public class ProjectsDateMap : EntityTypeConfiguration<ProjectsDate> { public ProjectsDateMap() { // Primary Key this.HasKey(t => t.OSProjectCode); // Properties this.Property(t => t.OSProjectCode) .IsRequired() .HasMaxLength(10); // Table & Column Mappings this.ToTable("ProjectsDates"); this.Property(t => t.OSProjectCode).HasColumnName("OSProjectCode"); this.Property(t => t.TargetStart).HasColumnName("TargetStart"); this.Property(t => t.EndDateOriginal).HasColumnName("EndDateOriginal"); this.Property(t => t.EndDateChangeControl).HasColumnName("EndDateChangeControl"); this.Property(t => t.EndDateActual).HasColumnName("EndDateActual"); this.Property(t => t.GoLiveAgreed).HasColumnName("GoLiveAgreed"); this.Property(t => t.GoLiveActual).HasColumnName("GoLiveActual"); // Relationships this.HasRequired(t => t.Project) .WithOptional(t => t.ProjectsDate); } } 

Why doesn't EF see my current API mapping?

+6
source share
3 answers

For some reason (probably an error), the FluentAPI needs a key that needs to be defined in a conditional way - that is, ClassName + Id, or in your case:

 ProjectsDateId 

In this way, metadata created by EF can confirm that this is related. Very annoying, but ...

+2
source

You need to have global binding or individual binding in OnModelCreating
( DbModelBuilder modelBuilder ).

Therefore, in your context file it will look something like this:

 public override void OnModelCreating(DbModelBuilder modelBuilder) { // global modelBuilder.Configurations.AddFromAssembly(GetType().Assembly); // individual modelBuilder.Configurations.Add(new ProjectsDateMap()); } 
+1
source

I fixed this by running the reverse engineering code from the EF power tools again. This seems to work from there, this seems to be a common problem that fires when your models are not configured correctly. This shame seems to be so general and just starts to mislead mistakes.

0
source

Source: https://habr.com/ru/post/944626/


All Articles