我正在使用EF Core和Identity。我创建了一个简单的应用程序:
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");
}
}
当我想添加迁移它给了我这个错误:
无法在“Person”上配置密钥,因为它是派生类型。必须在根类型“用户”上配置密钥。如果您不打算将“User”包含在模型中,请确保它不包含在上下文中的DbSet属性中,在对ModelBuilder的配置调用中引用,或者从包含的类型的导航属性引用在模型中。
我测试了这些变化:
1)如果所有者成为Person类型错误,但这不是我的选项,因为实际上User和Document在库中,我的最终应用程序使用该库,而Person在应用程序中。
2)如果ApplicationDbContext继承自DbContext,则错误发生。
有没有可用的解决方法?
如果在不更改Person
的情况下使用IdentityDbContext
和Document
,您可以从Document
实现一个新模型,并将其更改为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; }
}