none
Entity Framework inheritance and primary key RRS feed

  • Question

  • I am fairly new to Entity Framework (EF) and I am moving an app I created quite some time back from using a generated SQL mechanism to EF. My question is:

    I am using the code first approach to map my entities to a SQL table. For simplicity I am only going to involve two entities:

    public abstract class Person
    {
      public int PersonId { get; private set; }
      public string Forename { get; set; }
      public string Surname { get; set; }
    }
    public class Officer : Person
    {
      public int OfficerId { get; set; }
      public bool IsManager { get; set; }
    }

    As you can see the two classes are very lightweight. I made EF create the two entities and the representation it gives me is:

    Table: Person
    PersonId int PK
    Forename nvarchar(50)
    Surname nvarchar(50)
    
    Table: Officer
    PersonId int PK, FK
    IsManager bit
    OfficerId int

    The problem here is, I want the OfficerId to be the primary key of my Officer table. Now what I did is, I manually changed this within SQL Management Studio and within my ModelBuilder event I added the following:

    modelBuilder.Entity<Officer>().HasKey<int>(x => x.OfficerId).ToTable("Officer");

    Now it gives me an error stating the IDENTITY INSERT is off on the table but this isn't the case (as I adjusted this manually).

    Do I need to update my code somehow?

    How does EF know about schema changes using the code first approach?

    Thanks in advance, Onam.

    Monday, May 20, 2013 1:48 PM

Answers

All replies