简体   繁体   English

C#可查询 <T> 采取方法并不限制EF6实体的结果

[英]c# IQueryable<T>.Take method is not limiting result on EF6 entity

I'm using linq and EntityFramework 6 to limit the number of records returned from database. 我正在使用linq和EntityFramework 6来限制从数据库返回的记录数。

My test table, AuditLogs , has a total of 20 records. 我的测试表AuditLogs总共有20条记录。

If I write: 如果我写:

var auditLogsList = context.AuditLogs.Take(10); // Type is IQueryable<AuditLog>
var listValues = auditLogsList.ToList();
var count = listValues.Count; // Correct output = 10

I get listValues.Count equals to 10, which is the expected output. 我得到listValues.Count等于10,这是预期的输出。

But, I don't know why, if I call method Take in the next line : 但是,我不知道为什么, 如果我在下一行中调用方法Take

var auditLogsList = context.AuditLogs; // Type is IQueryable<AuditLog>
auditLogsList.Take(10);
var listValues = auditLogsList.ToList();
var count = listValues.Count; // Wrong output = 20

I get listValues.Count equals to 20, which is the total number of records of the table and it's not what I expect. 我得到listValues.Count等于20,这是表的记录总数,这不是我期望的。

I need to use it the second way. 我需要使用第二种方式。

Any ideas if it's a bug or am I missing something here? 有任何想法是错误还是我在这里错过了什么?

Note: I'm using .NET Framework 4.6.1 and Entity Framework 6 注意:我正在使用.NET Framework 4.6.1和Entity Framework 6

This line: 这行:

auditLogsList.Take(10);

Just creates an enumerator over 10 items - but you don't assign this anywhere, so it's thrown away. 只需创建一个包含10个项目的枚举数-但是您不会在任何地方分配它,因此将其丢弃。

Later on you do this: 稍后再执行此操作:

var listValues = auditLogsList.ToList();

This is working with the whole list - hence why you get 20. 这适用于整个列表-因此为什么要获得20。

If you just want to take 10 items (as a list), you can change the above line to: 如果您只想购买10件商品(作为清单),则可以将上面的行更改为:

var listValues = auditLogsList.Take(10).ToList();

Actually you are using Take wrong. 实际上,您正在使用“ Take错误”。 As MSDN link says that Take will Returns a specified number of contiguous elements from the start of a sequence. 正如MSDN链接所说, Take将从序列的开头返回指定数量的连续元素。 So you need to set it to a variable. 因此,您需要将其设置为变量。

var auditLogsList = context.AuditLogs; 
auditLogsList = auditLogsList.Take(10);
var listValues = auditLogsList.ToList();
var count = listValues.Count; // output = 10

Hope helps, 希望有帮助,

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

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