0

I want to implement batch delete (for performance reasons) in Entity framework like this:

context.ExecuteStoreCommand("DELETE FROM {0} WHERE {1} = {2}", tableName, columnName, columnValue);

I want to know how to get the column's name from the property.

[Column("ColumnName")]
public int PropertyName { get; set; }   

I Also use EF5 with Oracle provider.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
nazemian
  • 159
  • 1
  • 11

1 Answers1

4

You use Reflection.

public class MyClass
{
  [Column("ColumnName")]
  public int PropertyName { get; set; }   
}

Using Reflection:

public static string GetColumnName<T>(string propertyName)
{
    string result = null;

    if (string.IsNullOrWhiteSpace(propertyName))
    {
        throw new ArgumentNullException();
    }

    var tableType = typeof(T);
    var properties = tableType.GetProperties(BindingFlags.GetProperty 
                                             | BindingFlags.Instance 
                                             | BindingFlags.Public);

    var property = properties
      .Where(p => p.Name.Equals(propertyName, 
                               StringComparison.CurrentCultureIgnoreCase))
      .FirstOrDefault();

    if (property == null)
    {
      throw new Exception("PropertyName not found."); // bad example
    }
    else
    {
      result = property.Name;  //if no column attribute exists;

      var attributes = property.GetCustomAttributes();

      var attribute = attributes
        .Where(a => a is ColumnAttribute)
        .FirstOrDefault() as ColumnAttribute;

      if (attribute != null)
      {
        result = attribute.Name;
      }
    }
    return result;
}

For example:

public class MyClass
{
  [Column("ColumnName")]
  public int PropertyName { get; set; }   
}

var result = GetColumnName<MyClass>("PropertyName");
Console.WriteLine(result);

Result:

ColumnName

Erik Philips
  • 53,428
  • 11
  • 128
  • 150