我使用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.
}
謝謝您的幫助! Dan。
所以,你希望從一個潛在的更加複雜的表達式確定列名不僅僅是'X。 ColumnName'? – user7116 2011-06-07 18:26:39
嘗試調試,並把'property.Body作爲MemberExpression'融入腕錶,一旦你打'ErrorId'你可能會看到如何提取它 – oleksii 2011-06-07 18:39:18
@sixlettervariables正確。 – 2011-06-07 19:23:44