问题
I'm not sure whether this is possible in EF, but I am creating a bunch of classes and am trying to get EF to create the tables for me.
Now EF creates my tables fine, except for a minor issue. It created the tables as:
Person - PersonId (PK)
Foo - PersonId (PK) - FooId (INT)
Poo - PersonId (PK) - PooId (INT)
Ideally, I want the PersonId in tables Foo and Poo to be a foreign key not as the primary key. Is this possible? Tried using the ModelBuilder to do this via:
modelBuilder.Entity<Foo>().HasKey(x => x.FooId).ToTable("Foo");
public class Person
{
public int PersonId { get; private set; }
}
public class Foo : Person
{
public int FooId { get; private set; }
}
public class Poo : Person
{
public int PooId { get; private set; }
}
回答1:
The way you have implemented inheritance follows the table per type approach where the PK of the base class is the PK of derived classes and also a FK back to the base class.
You want PersonId in tables Foo and Poo to be a foreign key not as the primary key
, so by changing your configuration to from
modelBuilder.Entity<Foo>().HasKey(x => x.FooId).ToTable("Foo");
to
modelBuilder.Entity<Foo>().ToTable("Foo");
your database should look like this:
Person - PersonId (PK)
Foo - PersonId (PK, FK)
Poo - PersonId (PK, FK)
More reading on table per type inheritance.
来源:https://stackoverflow.com/questions/16585458/ef-inheritance-and-primary-keys