![](/img/trans.png)
[英]Get PropertyInfo of a parameter passed as lambda expression | Compact Framework, C#
[英]C# using PropertyInfo from reflection in a Lambda expression, error: not a valid property expression
我有一個循環,我只想循環遍歷具有特定裝飾器/屬性的對象的屬性,對於這些屬性,如果它們為空,則將它們從處於修改狀態的實體框架中刪除。 我可以讓循環工作,但不能刪除正在跟蹤的它們。
這是我的嘗試:
// Protect [NullUpdateIgnoreAttribute] attributes from nullification
var properties = updateCustomer.GetType().GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(NullUpdateIgnoreAttribute)));
foreach (var p in properties)
{
Console.WriteLine($"Verifying {p.Name}...");
object value = p.GetValue(updateCustomer, null);
if (value == null)
{
Console.WriteLine($"{p.Name} is null. Shielding attribute.");
loyalty.Entry(customer).Property(x => p.Name).IsModified = false;
}
}
由於我傳遞給loyalty.Entry().Property(x => here).IsModified = false
它失敗了。 顯然我不能直接使用propertyInfo
。 如果我通常這樣做,我只會傳遞x => x.propertyname
。 (例如x.firstname
)但我不能在這里對屬性名稱進行硬編碼,它可以是具有此屬性的多個屬性中的任何一個。
拋出的錯誤是:
"message": "The expression 'x => value(LCSApi.Customer+<>c__DisplayClass22_2).p.Name' is not a valid property expression. The expression should represent a simple property access: 't => t.MyProperty'. (Parameter 'propertyAccessExpression')",
有一個接受屬性名稱作為string
的重載,因此您可以使用它:
loyalty.Entry(customer).Property(p.Name).IsModified = false;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.