Search code examples
asp.netentity-frameworkasp.net-mvc-3ef-code-firstscaffolding

Scaffolding model with inheritance in ASP.NET MVC 3 and Entity Framework


I'm trying out the new scaffolding features in MVC 3, using Entity Framework Code First. My model looks like this:

public abstract class A
{
    public int Id { get; set; }
}

public class B : A
{
    public string Name { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<A> As { get; set; }
}

I create a new controller using the new controller wizard in MVC and select to scaffold type A. CRUD code is generated and I can successfully start the project in a webbrowser. When I try to create a new A, I get the following error message:

"Cannot create an abstract class"

which makes sense. A is abstract.

Can I use scaffolding to create B's and other inherited classes from A?


Solution

  • AFAIK you should add a

    using System.ComponentModel.DataAnnotations;
    
    [Table("TableNameForB")]
    public class B : A
    {
        public string Name { get; set; }
    }
    

    as attribute for your concrete class

    Find here a complete example

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations;
    
    namespace ZooLabPoco
    {
        public class Context : DbContext
        {
            public DbSet<Animal> Animals { get; set; }
            public DbSet<Zoo> Zoos { get; set; }
        }
    
        public class Zoo
        {
            public int Id { get; set; }
            public virtual ICollection<Animal> Animals { get; set; }
            public Zoo()
            {
                this.Animals = new List<Animal>();
            }
        }
    
        public abstract class Animal
        {
            public int Id { get; set; }
            public int ZooId { get; set; }
            public virtual Zoo Zoo { get; set; }
        }
    
        [Table("Lions")]
        public class Lions : Animal
        {
            public string LionName { get; set; }
        }
    
        [Table("Tigers")]
        public class Tigers : Animal
        {
            public string TigerName { get; set; }
            public int TailLength { get; set; }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
    
                var context = new Context();
                context.Database.Delete();
                context.Database.CreateIfNotExists();
    
    
                var zoo = new Zoo();
                zoo.Animals.Add(new Lions { LionName = "Fritz" });
                zoo.Animals.Add(new Lions { LionName = "Jerry" });
                zoo.Animals.Add(new Tigers { TigerName = "Pluto" });
    
                context.Zoos.Add(zoo);
                context.SaveChanges();
    
            }
        }
    }