首页 > 代码库 > EntityFramework Codefirst Select 查询指定列

EntityFramework Codefirst Select 查询指定列

本笔记解决如下两个问题:

1、查询返回指定列。

2、查询指定列时报错如下:

The entity or complex type ‘DataBase.AccordionModels‘ cannot be constructed in a LINQ to Entities query.

 

一、环境中类定义如下:
DataBaseContext,

  public DataBaseContext()            : base("default")        {        public DbSet<UserModels> UserContext { get; set; }        public DbSet<PigModels> PigContext { get; set; }        public DbSet<AccordionModels> AccordionContext { get; set; }        public DbSet<HrefModels> HrefContext { get; set; }         }

 AccordionModels:

  public  class AccordionModels    {       [Required]       [Key]       public string ID { get; set; }        [Required]        [Display(Name = "名称")]        public string title { get; set; }        [Display(Name = "icon")]        public string icon { get; set; }        [Display(Name = "顺序号")]        public int order { get; set; }        public virtual ICollection<HrefModels> Hrefs { get; set; }    }

HrefModels:

public class HrefModels    {       [Required]       [Key]       public string ID { get; set; }               [Required]        [Display(Name = "图标")]        public string icon { get; set; }        [Display(Name = "链接")]        public string link { get; set; }        [Display(Name = "名称")]        public string title { get; set; }        public int iFrame { get; set; }        public virtual AccordionModels  Accordion { get; set; }                  }

二、查询方法

(1)报错的查询方法:当采用如下写法查询时,会抛出异常 Message:The entity or complex type ‘DataBase.AccordionModels‘ cannot be constructed in a LINQ to Entities query.

 List<AccordionModels> accordions = new List<AccordionModels>();                    accordions = context.AccordionContext.Select(a => new AccordionModels()                    {                        ID = a.ID,                        title = a.title,                        icon = a.icon                    }).ToList();

 

可用如下两种方法:注意Select中的内容:1、新建一个实体类 AccordionView

 List<AccordionView> accordions = new List<AccordionView>();                    accordions = context.AccordionContext.Select(a => new AccordionView()                    {                        ID = a.ID,                        title = a.title,                        icon = a.icon                    }).ToList();


2、查询之后在转换

List<AccordionModels> AccordionModels = context.AccordionContext.Select(a => new           {           a.ID,         a.title,          a.icon       }).ToList()         .Select(b => new AccordionModels()         {         ID = b.icon,         title = b.title,        icon = b.icon         }).ToList();

 

EntityFramework Codefirst Select 查询指定列