Inheriting from auto-generated classes in Entity Framework

I am working on a project with MVC 4 and Entity Framework.

I created an object model with autogenerated classes from a database. But I need different names and methods for the classes in the models.

For example, it was generated by this class:

 public partial class tbl_Templates
        public tbl_Templates()
            this.tbl_Template_Sections = new HashSet<tbl_Template_Sections>();

         public int TemplateId { get; set; }



But I don't want to use this class, so I created my own class in Modeler:

public class Template : tbl_Templates
    public Template()
        : base()


    // I'll add custom methods later


Now how can I use this in my controller?

I tried:

  List<Template> Templates =db.tbl_Templates.Cast<Template>().ToList();


but I am getting an exception:

LINQ to Entities only supports listing of primitive or enumerated EDM types.


source to share

1 answer

You need Select

a Template

and display all properties. Something like that

List<Template> Templates = db.tbl_Templates.Select(x => new Template { 
                                                            .TemplateID = x.TemplateID 


If both types have the same property names, you can do this automatically with AutoMapper . They have docs on how to use the requested extensions. Here's a sample

Mapper.CreateMap<tbl_Templates, Template>();

List<Templates> Templates = db.tbl_Templates.Project().To<Template>().ToList();




All Articles