Examples of value injections for IDataReader and SqlCommand

    public class DataReaderInjection : KnownSourceValueInjection<IDataReader>
    {
        protected override void Inject(IDataReader source, object target, PropertyDescriptorCollection targetProps)
        {
            for (var i = 0; i < source.FieldCount; i++)
            {
                var activeTarget = targetProps.GetByName(source.GetName(i), true);
                if (activeTarget == null) continue;

                var value = source.GetValue(i);
                if (value == DBNull.Value) continue;

                activeTarget.SetValue(target, value);
            }
        }
    }

        public class CommandInjection : KnownTargetValueInjection<SqlCommand>
        {
            protected override void Inject(object source, ref SqlCommand cmd, PropertyDescriptorCollection sourceProps)
            {
                for (var i = 0; i < sourceProps.Count; i++)
                {
                    var prop = sourceProps[i];
                    if(prop.Name == "Id") continue;
                    
                    var dbType = SqlDbType.NVarChar;
                    if(prop.PropertyType == typeof(int)) dbType = SqlDbType.Int;
                    if(prop.PropertyType == typeof(long)) dbType = SqlDbType.BigInt;
                    
                    cmd.Parameters.Add(prop.Name, dbType).Value = prop.GetValue(source);
                }
                
            }
        }

usage


while (dr.Read())
 {
       var o = new User();
       o.InjectFrom<DataReaderInjection>(dr);
        yield return o;
 }

...

using (var cmd = conn.CreateCommand())
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "insertBank";
    cmd.InjectFrom<CommandInjection>(o);
   //instead of 
    //cmd.Parameters.Add("name", SqlDbType.NVarChar).Value = o.Name;
    //cmd.Parameters.Add("code", SqlDbType.NVarChar).Value = o.Code;
    conn.Open();

    return Convert.ToInt32(cmd.ExecuteScalar());
 }

Last edited Jun 16, 2010 at 2:56 PM by o, version 2

Comments

No comments yet.