简体   繁体   English

实体框架排除字段查询计数和POCO最佳方法

[英]Entity Framework Exclude Fields Query Count and POCO best way

I created a qr object to get total item count without getting all data from database and also if necessary to select MyViewModel list 我创建了一个qr对象,以获取项目总数,而无需从数据库中获取所有数据,还可以在需要时选择MyViewModel列表

var qr = dbSet.Select(o => 
                          new { ParentID = o.Parent.ID, o.Parent.Name, o.ID})
.Select(o => new MyViewModel(o.ParentID, o.Name, o.ID));

But when I tried qr.Count() and qr.ToList() they all run same query in database which is for items not only for items' count. 但是当我尝试使用qr.Count()qr.ToList()它们都在数据库中运行相同的查询,该查询不仅针对项目计数,还针对项目。

What is the best and fastest way to get 'MyViewModel' items' itself or items' count or both at the same time? 什么是同时获取“ MyViewModel”项目本身或项目计数或同时获得两者的最佳最快方法?

You have .AsEnumerable() call in your linq query. 您在linq查询中具有.AsEnumerable()调用。 That means that any translate-your-query-into-SQL stops right there, and anything after will not be translated to SQL. 这意味着任何将您的查询查询转换为SQL的操作都在那里停止,之后的任何操作都不会转换为SQL。 Therefore, the only query that will be run in your database is the retrieval of you complete dbSet . 因此,将在数据库中运行的唯一查询是对完整dbSet的检索。 If you want to only retrieve the count, than run the following linq query 如果只想检索计数,则运行以下linq查询

var qrCount = dbSet.Count();

The problem with this query is because it calls a constructor of MyViewModel in 此查询的问题是因为它在以下位置调用MyViewModel的构造函数

.Select(o => new MyViewModel(o.ParentID, o.Name, o.ID))

This call effectively converts your IQueryable to IEnumerable, as it is not possible to call a constructor from a query. 该调用有效地将您的IQueryable转换为IEnumerable,因为无法从查询中调用构造函数。

To avoid this conversion, use object initializer instead of constructor: 为了避免这种转换,请使用对象初始化程序而不是构造函数:

.Select(o => new MyViewModel 
        { 
            ParentID = o.ParentID, 
            Name = o.Name, 
            ID = o.ID
        })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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