Identity and inheritance Error On Migration: A key cannot be configured on 'Person' because it is a derived type

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

Question

I'm using EF Core and Identity. I have created a simple app:

public class Program
{
    static void Main(string[] args)
    {
    }
}


public class User : IdentityUser
{
}

public class Person : User
{
}

public class Document
{
    public int Id { get; set; }

    public User Owner { get; set; }
}


public class ApplicationDbContext : IdentityDbContext<Person>
{
    public DbSet<Person> Person { get; set; }
    public DbSet<Document> Document { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=.\;Database=EFCoreDemo;Trusted_Connection=True;MultipleActiveResultSets=true");
    }
}

When I want to add a migration It gave me this error:

A key cannot be configured on 'Person' because it is a derived type. The key must be configured on the root type 'User'. If you did not intend for 'User' to be included in the model, ensure that it is not included in a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation property on a type that is included in the model.

I have tested these changes:

1) If Owner became of type Person the error goes, but this is not an option for me because in fact User and Document are in a library and my final app use that library and Person is in the App.

2) If ApplicationDbContext inherits from DbContext the error goes.

Is there any workaround available?

1
0
9/13/2018 1:50:18 PM

Popular Answer

For using Person and IdentityDbContext without changing Document, you could implement a new model from Document, and change it to Person.

    public class ApplicationDbContextTest : IdentityDbContext<Person>
{
    public DbSet<MyDocument> Document { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFCoreDemo;Trusted_Connection=True;MultipleActiveResultSets=true");
    }
}
public class User : IdentityUser
{
}

public class Person : User
{
}
public class MyDocument:Document
{
    public new Person Owner { get; set; }
}
public class Document
{
    public int Id { get; set; }

    public User Owner { get; set; }
}
2
9/14/2018 3:01:54 AM


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