我有一个实体集,当我把它打印到控制台时,它看起来像这样:
EntitySet {entityContext: resource_dbEntities, _expression: undefined, elementType: function, person: function, createNew:function…}
_defaultType: function person(){
_expression: EntitySetExpression
collectionName: "person"
createNew: function person(){
elementType: function person(){
entityContext: resource_dbEntities
eventHandlers: undefined
name: "person"
person: function person(){
roles: undefined
stateManager: EntityStateManager
tableName: "person"
tableOptions: undefined
__proto__: EntitySet
是否有一种方法可以找出entityset中有多少个元素?我不确定它是否被填充,但我不确定如何检查。
像"myEntitySet.size"?
如果您无论如何都要查询整个数据库,正如您在评论中提到的,您可以查询DbSet的计数,尽管这会从数据库中获取所有行。
static void Main(string[] args)
{
using (var context = new EntityContext())
{
context.Entities.Add(new MyEntity());
context.Entities.Add(new MyEntity());
var myEntityCount = context.Entities.Count();
Console.WriteLine("The context now tracks {0} entities", context.Entities.Local.Count);
context.SaveChanges();
}
using (var context = new EntityContext())
{
Console.WriteLine("The db had {0} entities when I queried it", context.Entities.Count());
context.SaveChanges();
}
}
class MyEntity
{
public int MyEntityId { get; private set; }
}
class EntityContext:DbContext
{
public DbSet<MyEntity> Entities { get; set; }
}
对于数据库中的大量数据,您不会想要这样做,并且您将不得不诉诸于编写sql来返回表的计数,而不需要获取所有内容。