简体   繁体   中英

Inheriting from auto-generated classes in Entity Framework

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

I have created the entity model with autogenerated classes from database. But, I want different names and methods for classes in the Models.

For instance, it has been generated 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 dont want to use this class, so I have created my own class in the modeler:

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

    }

    // I'll add custom methods later
}

Now, how can I use this one in the controller?

I tried:

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

but i get the exception:

LINQ to Entities only supports casting EDM primitive or enumeration types.

You need to Select a Template and map all the properties across. Something like this

List<Template> Templates = db.tbl_Templates.Select(x => new Template { 
                                                            .TemplateID = x.TemplateID 
                                                   }).ToList();

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

Mapper.CreateMap<tbl_Templates, Template>();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM