[MVC 3] ObjectSet Extension Method–CountAll

I find myself when using Entity Framework, before accessing any of Objects i have various try/catch methods, due to the amount of exceptions that “bubble” up.


Now before i try and access my ObjectSet’s within my ObjectContext i usually make sure there are objects there to begin with. I usually do something like:



if ((db.RoomTypes.Count(i => i.Type_Code == room.Type)) > 0)
    roomType = db.RoomTypes.SingleOrDefault(i => i.Type_Code == room.Type);
    r.RoomType = roomType.Type_Name;




Now this is fine for when I’m trying to select against say, an id. This doesn’t work when i want to return all records from my ObjectSet. So i have come up with an extension method to the said ObjectSet:

        #region CountAll
        public static int CountAll<TEntity>(this ObjectSet<TEntity> objectSet) 
where TEntity : class { int _count = 0; foreach (var ObjectSet in objectSet) { if (objectSet != null) { _count++; } } return _count; } #endregion



Take note of the TEntity class constraint. Some little background. When you create your EF classes based on your database, there are various classes that are created.

Here is another example, db.Rooms being my ObjectContext:


Room room = db.Rooms.SingleOrDefault(r => r.Unique_Key == id);


If you look at the definition of Rooms (ObjectSet – a table), this is the collection of Room:


public ObjectSet<Room> Rooms
         if ((_Rooms == null))
             _Rooms = base.CreateObjectSet<Room>("Rooms");
         return _Rooms;


If you look at the definition of Room generic parameter, represents a row in the table Room:

public partial class Room : EntityObject


So we know in essence the ObjectSet is the table and EntityObject is a row. So now we know this you can interrogate the definition of ObjectSet:

public class ObjectSet<TEntity> : ObjectQuery<TEntity>, IObjectSet<TEntity>,
IQueryable<TEntity>,IEnumerable<TEntity>, IQueryable, IEnumerable
where TEntity : class { }

So there’s your TEntity you need for your extension method constraint. Now you know why we have done what we have done for the Extension Method, here is how to use it:

  if ((db.Properties.CountAll()) > 0)
     //--code here

So we can CountAll the ObjectsSets (Rows) within Properties, if there are more than 0, the do something (Like query the data).

Anyway, i hope this helps.




Enhanced by Zemanta