0

I have an entity set that looks like this when I print it to the console:

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

Is there a way to find out how many elements are in the entityset? I'm not sure it's being populated but am unsure how to check.

Something like "myEntitySet.size"?

AllieCat
  • 3,890
  • 10
  • 31
  • 45
  • Are you trying to figure out how many rows that table has in the database or how many instances (entities) are stored locally in the context? – moranlf Jun 13 '13 at 19:18
  • The latter. Though they should be the same, right - since the database populates the context... – AllieCat Jun 13 '13 at 20:05
  • They are not the same. Yea, the context is populated by the database, but only with the results of your queries. A query will usually not retrieve all rows from the table. You can also populate the context with entities that you create in your application. These will only be added to the db when you call 'SaveChagnes()'. So, do you want to know the number of rows in the db table, or the number of entities of type person that are tracked by the context? – moranlf Jun 13 '13 at 20:26
  • Okay - right now I'm querying for the entire database - so they should be the same. But I want the number of entities of type person. – AllieCat Jun 13 '13 at 20:43

1 Answers1

0

If you're querying against the whole database anyway, as you mentioned in your comment, you can go with querying the DbSet's Count, even though that will fetch all rows from the database.

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; }
}

With large amount of data in your db, you wouldn't want to do that, and you will have to resort to writing sql to return just the count of the table, without fetching everything.

moranlf
  • 554
  • 5
  • 19