How to not declare key in root model in EntityFramework core

.net c# entity-framework entity-framework-core

Question

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.

1
1
9/7/2018 12:04:18 PM

Popular Answer

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.

0
4/29/2019 12:43:29 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow