Выражение члена LINQ получение имени столбца

Здравствуйте,

Я использую LINQ и EF с C # 4.0. Я перетащил основную таблицу ELMAH в EF (построенную и сохраненную много раз).Все работает так, как и следовало ожидать.

Но я попытался быть слишком амбициозным и мне нужна небольшая помощь - я пытаюсь получить имя столбца из выражения, которое передается как переменная.

Я хочу, чтобы это:

Передайте: x => x.ErrorId

и получите: "ErrorId"

public void GetColumnName(Expression<Func<T, object>> property)
{
  // The parameter passed in x=>x.Message
  // Message works fine (probably because its a simple string) using:
  string columnName = (property.Body as MemberExpression).Member.Name;

  // But if I attempt to use the Guid or the date field then it
  // is passed in as x => Convert(x.TimeUtc)
  // As a result the above code generates a NullReference exception
  // i.e. {"Object reference not set to an instance of an object."}

  // What is the correct code here to extract the column name generically?
  // Ideally in a way that won't bite me again in the future.

}

Спасибо за вашу помощь! Дан.

6
задан user7116 7 June 2011 в 18:27
поделиться