code_junkie

Obtain max length for a “string” column using LINQ to SQL

Nov 12th, 2011
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. int maxLength = dc.MyTable.Max(x => x.MyColumn.Length);
  2.  
  3. select max_length from sys.columns as c inner join sys.objects o on c.object_id = o.object_id where o.name = 'myTable' and c.name = 'myColumn'
  4.  
  5. public static int GetLengthLimit(Type type, string field) //definition changed so we no longer need the object reference
  6. //Type type = obj.GetType(); //comment this line
  7.  
  8. int i = GetLengthLimit(typeof(Pet), "Name");
  9.  
  10. public static int GetLengthLimit(Model.RIVFeedsEntities ent, string table, string field)
  11. {
  12. int maxLength = 0; // default value = we can't determine the length
  13.  
  14. // Connect to the meta data...
  15. MetadataWorkspace mw = ent.MetadataWorkspace;
  16.  
  17. // Force a read of the model (just in case)...
  18. // http://thedatafarm.com/blog/data-access/quick-trick-for-forcing-metadataworkspace-itemcollections-to-load/
  19. var q = ent.Clients;
  20. string n = q.ToTraceString();
  21.  
  22. // Get the items (tables, views, etc)...
  23. var items = mw.GetItems<EntityType>(DataSpace.SSpace);
  24. foreach (var i in items)
  25. {
  26. if (i.Name.Equals(table, StringComparison.CurrentCultureIgnoreCase))
  27. {
  28. // wrapped in try/catch for other data types that don't have a MaxLength...
  29. try
  30. {
  31. string val = i.Properties[field].TypeUsage.Facets["MaxLength"].Value.ToString();
  32. int.TryParse(val, out maxLength);
  33. }
  34. catch
  35. {
  36. maxLength = 0;
  37. }
  38. break;
  39. }
  40. }
  41.  
  42. return maxLength;
  43. }
Add Comment
Please, Sign In to add comment