从ColumnAttribute检索名称值以进行实体框架批量删除

时间:2014-10-17 16:38:56

标签: c# entity-framework reflection entity-framework-5 odac

我想在Entity框架中实现批量删除(出于性能原因),如下所示:

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

我想知道如何从属性中获取列的名称。

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

我还将EF5与Oracle提供商一起使用。

1 个答案:

答案 0 :(得分:3)

您使用Reflection

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

使用反思:

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;
}

例如:

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

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

结果:

  

的ColumnName