Archive

Posts Tagged ‘Extension Method’

[MVC 3] ObjectSet Extension Method–CountAll

September 16, 2011 Leave a comment

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
 {
     get
     {
         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:

try
{
  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

[MVC 3] ModelState ModelErrorCollection Debug–Extension Method

September 6, 2011 2 comments

In the last i described a way of using a static method to obtain which model field is causing your ModelState to be invalid. My good friend Shaw Young said that a Extension Method would be another way of doing this. And thinking of it, it makes more sense and a better and cleaner implementation.

So here is that piece of code again:

if (ModelState.IsValid)
{

  //—Your code here
}
else {
    Debug.ModelStateErrors( ModelState);
    ModelState.ModelStateErrors();
}

So now instead of a Debug.ModelStateErrors, there is a Extension Method ModelStateErrors referenced by the object itself.

And here is the code:

public static void ModelStateErrors (this ModelStateDictionary modelState)
{
    var errors = modelState.Where(a => a.Value.Errors.Count > 0)
        .Select(b => new { b.Key, b.Value.Errors })
        .ToArray();

    foreach (var modelStateErrors in errors)
    {
        int count = modelStateErrors.Errors.Count();
        System.Diagnostics.Debug.WriteLine("...Errored When Binding.",        
        modelStateErrors.Key.ToString());

    }

}

There you are! The only difference is the implementation of the static method itself. The actual code is the same.

Enhanced by Zemanta
Categories: Tip Tags: , ,

[MVC 3] ModelState ModelErrorCollection Debug

September 5, 2011 2 comments

UPDATE: Dan Kendall kindly done a gist of the code which can be found here if you need it which is related to this post:

https://gist.github.com/3699804

We all use the ModelState.IsValid before we commit any changes to our Entity Framework ObjectContext to update our data source. But what is ModelState.IsValid? Well basically ModelState says…

“Yes, all models have binded successfully from the view”

But what happens when we the ModelState is NOT valid. Well, I  have a little static method So you can write to the Output window to see what the property name is, so you can fix it quickly.

if (ModelState.IsValid)
{
   ///—- Your code.
}
else {
    Debug.ModelStateErrors( ModelState);

}

Now my method, Debug.ModelStateErrors consists of an Anon Type which i use a LINQ to abstract the ModelErrorCollection from the ModelState. I then print out the Key from the Dictionary to the Output window.  Example on the 2nd image which is property.PropertyType is the model field.

#if DEBUG
       /// <summary> 
 /// Output the properties which are causing the issues when 
 /// the model is binding. 
 /// </summary> public static void ModelStateErrors (ModelStateDictionary modelState)
        {
            var errors = modelState.Where(a => a.Value.Errors.Count > 0)
                .Select(b => new { b.Key, b.Value.Errors })
                .ToArray();

            foreach (var modelStateErrors in errors)
            {
                 System.Diagnostics.Debug.WriteLine("...Errored When Binding.",                                  modelStateErrors.Key.ToString());

            }

        }
#endif #endregion 

Capture

Enhanced by Zemanta
Categories: Tip Tags: , ,
Follow

Get every new post delivered to your Inbox.

Join 281 other followers

%d bloggers like this: