5

I am looking to refactor this method (from Massive.cs by Rob Conery):

public static void AddParam(this DbCommand cmd, object item) {
    var p = cmd.CreateParameter();
    p.ParameterName = string.Format("@{0}", cmd.Parameters.Count);
    if (item == null) {
        p.Value = DBNull.Value;
    } else {
        if (item.GetType() == typeof(Guid)) {
            p.Value = item.ToString();
            p.DbType = DbType.String;
            p.Size = 4000;
        } else if (item.GetType() == typeof(ExpandoObject)) {
            var d = (IDictionary<string, object>)item;
            p.Value = d.Values.FirstOrDefault();
        } else {
            p.Value = item;
        }
        //from DataChomp
        if (item.GetType() == typeof(string))
            p.Size = 4000;
    }
    cmd.Parameters.Add(p);
}

Likely adding a check for Geography type will fix my issue with ExecuteNonQuery and spatial data types, but what type would I check for?

if (item.GetType() == typeof(//WhatType?//)) {}

Chaddeus
  • 13,134
  • 29
  • 104
  • 162

2 Answers2

7

SqlGeography is what you're looking for, I believe.

Dan Gartner
  • 922
  • 5
  • 6
  • Thanks, once I get back to my workstation, I'll check this... seems like a great candidate though. Appreciate your time. – Chaddeus Apr 14 '11 at 00:59
3

How about this?

if (item.GetType() == typeof(Microsoft.SqlServer.Types.SqlGeography)) 
{
     SqlParameter p = new SqlParameter();
     p.SqlDbType = System.Data.SqlDbType.Udt;
     p.UdtTypeName = "geography";
     p.Value = value;
}
alwayslearning
  • 4,493
  • 6
  • 35
  • 47