Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 261
Chris Moschini Avatar asked Sep 08 '12 20:09

Chris Moschini


1 Answers

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;
like image 170
Chris Moschini Avatar answered Sep 19 '22 18:09

Chris Moschini