Mirhat
Mirhat

Reputation: 381

How to not declare key in root model in EntityFramework core

I would like to create a base model with some common fields for all tables, like CreatedBy and ModifiedBy, but I don't want to add the key to that base model.

public abstract class BaseModel
{
    public string CreatedBy { get; set; }

    public string ModifiedBy { get; set; }
}

public class Student : BaseModel
{
    [Key, Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string FirstName { get; set; }
}

I am getting this error message

The derived type cannot have KeyAttribute on property 'Id' since the primary key can only be declared on the root type

.

I am using Entity Framework Core 2.

Upvotes: 4

Views: 2574

Answers (1)

Alexei - check Codidact
Alexei - check Codidact

Reputation: 23078

I have received the same error and came here. Your code is not complete, but I can provide some insight based on what I have experienced. Possible causes:

  1. DbSet<BaseModel> in your context

  2. Foreign key involving base model:

    [ForeignKey(nameof(BaseModel)] public int SomeId { get; set; }

    public BaseModel SomeNavigationProperty { get; set; }

  3. Some (navigation) property using BaseModel in any of your models (used in the db context)

    public BaseModel SomeModel { get; set; }

All these will make add-migration think that BaseModel is a model to be added and dealt with in the database context and will generate this error.

Upvotes: 2

Related Questions