Contact Us

Contact Us

How to get length of a LINQ to SQL class’s attribute

How to get the length of a LINQ to SQL class’s attribute?

The following code snippet will return the length of a DB field from a SQL to Linq class object. Pass the instance of the object and name of the DB field.

 

public static int GetLengthLimit(object obj, string field) {
 int dblenint = 0; // default value = we can't determine the length
 Type type = obj.GetType();
 PropertyInfo prop = type.GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
 // Find the Linq 'Column' attribute
 // e.g. [Column(Storage="_FileName", DbType="NChar(256) NOT NULL", CanBeNull=false)]
 object[] info = prop.GetCustomAttributes(typeof(ColumnAttribute), true);
 // Assume there is just one
 if (info.Length == 1) {
  ColumnAttribute ca = (ColumnAttribute) info[0];
  string dbtype = ca.DbType.ToUpper();
  if (dbtype.StartsWith("CHAR") || dbtype.StartsWith("NCHAR") || dbtype.StartsWith("NVARCHAR") || dbtype.StartsWith("VARCHAR")) {
   int index1 = dbtype.IndexOf("(");
   int index2 = dbtype.IndexOf(")");
   string dblen = dbtype.Substring(index1 + 1, index2 - index1 - 1);
   int.TryParse(dblen, out dblenint);
  } else if (dbtype.StartsWith("DATETIME")) {
   dblenint = 8;
  }
 }
 return dblenint;
}

 

Healthcare software development, HL7 Interface, EMR/EHR integration, mHealth, HIPAA compliant