I'm currently in possession of one VS solution made by someone else that use Entity Framework. This solution include one console application to test the main features that runs just fine.
However, if I try to call these main feature in my own VS solution (with the dll references), I have the following error message:
ConsoleApplication1.Persistence.FileTemplateModel: EntityType 'FileTemplateModel' has no key defined. Define the key for this EntityType.
I searched through Internet and I found this one that seems very similar: EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType
However, it seems that it’s something else since the console application defines one TestContext that inherits the FrameworkDbContext that inherits DbContext.
public partial class FrameworkDbContext : DbContext
{
public FrameworkDbContext(): base("DefaultConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
public class TestContext : FrameworkDbContext
{
public override UserModel CurrentUser
{
get
{
if (_currentUser == null)
{
EDIT: The FileTemplateModel from the VS solution (made by someone else) already declare which property is the primary key:
[Table("File.Template", Schema = "Template")]
public class FileTemplateModel : _Auditable
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
[HiddenInput(DisplayValue = false)]
public int FileTemplateId { get; set; }
[Required]
[Display(Name = "Type")]
public int FileTemplateTypeId { get; set; }
[ForeignKey("FileTemplateTypeId")]
public virtual FileTemplateTypeModel FileTemplateType { get; set; }
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
In fact, as I already mentioned, everything works just fine if I run the console application test included it that VS solution, meaning that FileTemplateModel is correctly declared. The problem is when I try to build my own console application in one VS solution completely separated.
GOT IT: Well, it seems that the model’s annotations are lost somehow. So I decided to force them with code first at OnModelCreating:
modelBuilder.Entity<FileTemplateModel>().HasKey(x => x.FileTemplateId);
Everything works just fine now, but I wonder: why those annotations at FileTemplateModel model are not enough to define the primary key?