Search code examples
asp.net-mvcentity-frameworkef-database-first

How can I implement inheritance with EF database-first


I have this simple class:

CREATE TABLE [dbo].[Movie] (
  [MovieId] INT             IDENTITY (1, 1) NOT NULL,
[Title]   NVARCHAR (200)  NULL,
[Genre]   NVARCHAR (200)  NULL,
[Date]    DATE            NULL,
[Price]   DECIMAL (18, 2) NULL,
CONSTRAINT [PK_dbo.Movies] PRIMARY KEY CLUSTERED ([MovieId] ASC)
);

Now I want to implement a SpecialMovie... that has one additional property called Special.

I am working with a database-first approach.

I have tried to find some tutorials but nothing was really helpful.

I have a SQL Server 2008 book and it says nothing about inheritance... isn't inheritance an important thing in SQL ? Its kind of strange that it has nothing on inheritance....


Solution

  • Implementing inheritance in EF is exactly the same as normal class inheritance, so in this case :

    public class Movie
    {
    public int MovieID {get; set;}
    //.....
    }
    
    public class SpecialMovie : Movie
    {
    public int SpecialMovieID {get; set;}
    //.....
    
    }
    
     public class MovieContext : DbContext
        {
            public DbSet<SpecialMovie> SpecialMovies { get; set; }
            public DbSet<Movie> Movies{ get; set; }
        }
    

    Note that there isn't really a corresponding inheritance structure in a relational database such as SQL Server. Thus EF will implement inheritance in several ways Table per Hierarchy is probably the most performant but it will denormalize the data so that the data for both the SpecialMovie and Movie classes reside in the same table and EF adds a descriminator field to distinguish between the two classes. EF also offers Table-per-type and Table per Concrete Type. There is a good description of all three here http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx .