2

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.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Mirhat
  • 341
  • 3
  • 7
  • 20
  • 4
    Just don't map the `BaseModel` class, only map the sub classes. Or don't use a base class and visible properties at all. These properties are perfect candidates for [shadow properties](https://stackoverflow.com/a/52021425/861716) – Gert Arnold Sep 07 '18 at 10:36
  • The main motivation for all of this is to add IsDeleted property in the BaseModel and to have Query filter like this `modelBuilder.Entity().HasQueryFilter(p => !p.IsDeleted)` is there any way to implement this – Mirhat Sep 07 '18 at 12:34
  • 1
    Yes. This answer on Soft Delete with Shadow Properties and Query Filters: https://stackoverflow.com/questions/47673524/ef-core-soft-delete-with-shadow-properties-and-query-filters – David Browne - Microsoft Sep 07 '18 at 13:55
  • @Mirhat problem is in your `DbContext` class. Please share your `DbContext` class code. – TanvirArjel Sep 07 '18 at 17:53

1 Answers1

2

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.

Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164