0

当我将它打印到控制台时,我有一个如下所示的实体集:

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

有没有办法找出实体集中有多少元素?我不确定它是否被填充,但不确定如何检查。

像“myEntitySet.size”这样的东西?

4

1 回答 1

0

如果您要查询整个数据库,正如您在评论中提到的那样,您可以查询 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 来仅返回表的计数,而无需获取所有内容。

于 2013-06-13T21:48:32.250 回答