查找EntitySet的大小?

时间:2013-06-13 19:03:14

标签: xml entity-framework odata entityset

当我将它打印到控制台时,我有一个看起来像这样的实体集:

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”之类的东西?

1 个答案:

答案 0 :(得分:0)

如果您正在查询整个数据库,正如您在评论中提到的那样,您可以查询DbSet的Count,即使这将从数据库中获取所有行。

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来返回表的计数,而不是取出所有内容。