2

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; }
}
John Willemse
  • 6,608
  • 7
  • 31
  • 45
Dr Schizo
  • 4,045
  • 7
  • 38
  • 77

1 Answers1

3

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.

MattSull
  • 5,514
  • 5
  • 46
  • 68
  • Is it possible then to have PersonId to being the FK only and to have FooId in the Foo table to be a PK? – Dr Schizo May 16 '13 at 11:21
  • Yes, it is possible. But in this case you should create database by your hand and use code first only to map entities to existing database. – Kirill Bestemyanov May 16 '13 at 11:34
  • I wasn't entirely sure if what you wanted to do can be done using code first, and @KirillBestemyanov's answer confirms that. Look at this link where Ladislav explains how to map TPT using the designer http://stackoverflow.com/questions/5439273/how-to-map-table-per-type-tpt-inheritance-in-entity-designer/5443033#5443033 – MattSull May 16 '13 at 11:36
  • Thank you. I am installing SP1 and checking the modelling tool that is available. – Dr Schizo May 17 '13 at 12:28