views:

22

answers:

1

I want to have a class that defines my parameter data for a stored procedure. It's going to be a very simple object:

public class MyQueryData : SprocObjectBase
{
   public int Value1 { get; set; }
   public string Value2 { get; set; }
   public bool Value3 { get; set; }
...
}

It will inherit from a base class with shared values, like the name.

public abstract class SprocObjectBase
{
   public string SprocName { get; set; }
}

Simple types for easy conversion. But, there will be more than one of these objects, and each one different.

Then, I want to be able to iterate the properties of the object and add the parameter values to my query, assuming the property names are my sproc parameter names. So, my code looks something like this:

    public void Execute<T>(T entity) where T : SprocObjectBase
    {
        IQuery query = Session.GetNamedQuery(entity.SprocName);

        var properties = typeof(T).GetProperties();

        foreach (var prop in properties)
        {
            //??????????????
        }

        query.ExecuteUpdate();
    }

My question is, how do I use query.SetParameter<>() with the property info inside my foreach loop to generically add each property as a parameter to the stored procedure?

EDIT: My current usage, which does not compile, looks like this:

query.SetParameter<prop.GetType()>(prop.Name, prop.GetValue(entity, null));
+1  A: 

I didn't try, but something like this should work:

    foreach (var prop in properties)
    {
        query.SetParameter(prop.Name, prop.GetValue(entity, null));
    }

By the way, until now you don't need to make the method generic. You are using reflection anyway.

Stefan Steinegger
doh, I didn't see that usage. User error. Thanks Stefan.
Josh