Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private string GenerateInsertStatementForEntity(object entity)
- {
- Type entityType = entity.GetType();
- string tableName = ((TableAttribute)entityType.GetCustomAttributes(false)[0]).Name;
- var dict = new Dictionary<string, object>();
- foreach (var property in entityType.GetProperties())
- {
- var attributes = property.GetCustomAttributes(typeof(ColumnAttribute), false);
- if (attributes != null && attributes.Length != 0)
- {
- ColumnAttribute colAttr = (ColumnAttribute)attributes[0];
- string colName = colAttr.Name ?? property.Name;
- string value = property.GetValue(entity, null);
- dict[colName] = value;
- }
- }
- var keysStrs = dict.Keys.Select(k => String.Format("{0}", k));
- var valuesStrs = new List<string>();
- foreach (var key in dict.Keys)
- {
- object value = dict[key];
- if (value == null)
- {
- valuesStrs.Add("null");
- }
- else if (value is string)
- {
- valuesStrs.Add(String.Format("'{0}'", value));
- }
- else
- {
- valuesStrs.Add(value.ToString());
- }
- }
- return String.Format("INSERT INTO {0}({1}) VALUES ({2})",
- tableName,
- String.Join(",", keysStrs.ToArray()),
- String.Join(",", valuesStrs.ToArray()));
- }
Advertisement
Add Comment
Please, Sign In to add comment