Entity Framework 4.3.1 -> 5.0 Exception: “EntityType has no key defined. Define the key for this EntityType.”

StackOverflow https://stackoverflow.com/questions/12334044

Question

In Entity Framework 4.3.1 I had the following Models, and they worked fine:

public class BaseUser
{
    [Key]
    [MaxLength(100)]
    public string Username { get; set; }
}

[Table("AppUser")] // Ensures EF Code First uses Table-per-Type
public class AppUser : BaseUser
{
    [MaxLength(200)]
    public string About { get; set; }
}

After upgrading to EF 5.0, I get the following exception when I try to run this application and access the associated DbContext:

EntityType 'AppUser' has no key defined. Define the key for this EntityType.

How do I resolve this issue? This appears to be a regression.

Was it helpful?

Solution

This Exception is caused by mixing EF versions.

BaseUser was defined in a shared Project that uses EF 4.3.1. AppUser was in a Project using EF 5.0. This confusing Exception is a result of trying to inherit from a model in a Project that has not been upgraded to EF 5.0. Splitting the shared project and upgrading the one referenced here resolved the issue.

If others run into this it's worth pointing out that upgrading is a bit awkward. Since NuGet doesn't seem to notice the need for an upgrade, it lets you install EF 5.0 on top of it, lists the new version as 4.4 after install, and requires you to include both of the following using statements in your Model classes since some of the EF data annotations were moved (redirected), and some were not:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top