0

I am using EF Core 8 Preview 1.2 and CommunityToolkit.Mvvm 8.1.0 in a WASDK 1.2/WinUI 3 C# desktop app project.

Here are my models:

public abstract partial class Person : ObservableObject
{
    [ObservableProperty][Key] int personId;
    [ObservableProperty] string name;
}
public partial class Employee : Person
{
    [ObservableProperty] string employeeId;
    [ObservableProperty] string department;
}
public partial class Teacher : Employee
{
    [ObservableProperty] string teacherId;
    [ObservableProperty] ObservableCollection<string> competencies;
}

Here is my DbContext:

public class PersonDbContext : DbContext
{
    public DbSet<Person> Person { get; set; }
    public DbSet<Employee> Employee { get; set; }
    public DbSet<Teacher> Teacher { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().UseTpcMappingStrategy();
    }
}

Here is the error when running Add-Migration in the PM console:

PM> Add-Migration D Build started... Build succeeded.

Unable to create a 'DbContext' of type ''. The exception 'The entity type 'ObservableCollection' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Error is not supposed to occur because Teacher inherits from Employee which inherits from Person. Person base class has the [Key] annotation which tells EF core the primary key to use. Am I missing something here? The project compiles without any errors. It's the migration that fails.

EF Core is supposed to work.

  • Make all these *public properties* (currently they are *private fields*) – Ivan Stoev Mar 13 '23 at 02:16
  • the private fields will be converted to public properties with the help of Mvvm by utilizing the [ObservableProperty] annotation. – user21311740 Mar 13 '23 at 03:14
  • It doesn't matter what Mvvm will do, but EF Core needs public properties in **these** classes in order to include them in the model. Also collections of primitive types are not supported, EF considers `ObservableCollection` to be entity, thus requires key etc. – Ivan Stoev Mar 13 '23 at 06:42

0 Answers0