nyk0r

Generate INSERT SQL for Entity LINQ2SQL without ID

Aug 11th, 2011
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.16 KB | None | 0 0
  1. private string GenerateInsertStatementForEntity(object entity)
  2. {
  3.     Type entityType = entity.GetType();
  4.     string tableName = ((TableAttribute)entityType.GetCustomAttributes(false)[0]).Name;
  5.  
  6.     var dict = new Dictionary<string, object>();
  7.     foreach (var property in entityType.GetProperties())
  8.     {
  9.         var attributes = property.GetCustomAttributes(typeof(ColumnAttribute), false);
  10.         if (attributes != null && attributes.Length != 0)
  11.         {
  12.             ColumnAttribute colAttr = (ColumnAttribute)attributes[0];
  13.             string colName = colAttr.Name ?? property.Name;
  14.             string value = property.GetValue(entity, null);
  15.  
  16.             dict[colName] = value;
  17.         }
  18.     }
  19.  
  20.     var keysStrs = dict.Keys.Select(k => String.Format("{0}", k));
  21.     var valuesStrs = new List<string>();
  22.     foreach (var key in dict.Keys)
  23.     {
  24.         object value = dict[key];
  25.         if (value == null)
  26.         {
  27.             valuesStrs.Add("null");
  28.         }
  29.         else if (value is string)
  30.         {
  31.             valuesStrs.Add(String.Format("'{0}'", value));
  32.         }
  33.         else
  34.         {
  35.             valuesStrs.Add(value.ToString());
  36.         }
  37.     }
  38.  
  39.     return String.Format("INSERT INTO {0}({1}) VALUES ({2})",
  40.         tableName,
  41.         String.Join(",", keysStrs.ToArray()),
  42.         String.Join(",", valuesStrs.ToArray()));
  43. }
Advertisement
Add Comment
Please, Sign In to add comment