[英]Getting information on current property via Reflection inside attribute
[英]attribute on virtual property not showing via reflection
我有一個帶有屬性的EntityFramework模型,用於驗證字段。
private person tipProvider;
[Required]
[ForeignKey("TipProviderId")]
public virtual person TipProvider
{
get { return tipProvider; }
set
{
tipProvider = value;
ValidateProperty(MethodBase.GetCurrentMethod().Name.Replace("set_", ""));
raisePropertyChanged(MethodBase.GetCurrentMethod().Name.Replace("set_", ""));
}
}
我得到了PropertyInfo
,然后是它的驗證屬性,用於驗證屬性:
public virtual void ValidateProperty(string property)
{
errors[property].Clear();
var propertyInfo = this.GetType().GetProperty(property);
var propertyValue = propertyInfo.GetValue(this);
var validationAttributes = propertyInfo.GetCustomAttributes(true).OfType<ValidationAttribute>();
foreach (var validationAttribute in validationAttributes)
{
if (!validationAttribute.IsValid(propertyValue))
{
errors[property].Add(validationAttribute.FormatErrorMessage(string.Empty));
}
}
raiseErrorsChanged(property);
}
當屬性是虛擬的時,我無法通過反射找到屬性。 如果刪除了virtual關鍵字,則會找到屬性。
我真的對這種行為感到困惑。 為什么不能將屬性應用於虛擬屬性?
我不知道您到底想做什么,但是根據我從EntityFramework所知道的,問題不完全是您在想什么。 您可以將屬性應用於虛擬屬性,並且可以通過反射毫無問題地恢復它們,就像您所做的那樣。
但是在EF實體上,當您將某個屬性標記為虛擬時, 您正在向EF定義該屬性為導航屬性 (用於訪問關系中的外鍵數據並將其作為子實體檢索的屬性)。
然后,當您在運行時從數據庫上下文中獲取該實體的新實例並訪問該屬性時,EF將創建一個從您的類派生的新類(動態代理),並使用它代替原始類。 實體框架這樣做是為了維護“延遲加載”關系的概念-避免在不需要時加載整個新的依賴實體樹。
因為EF從您的實體派生了一個新類,並且該屬性被該屬性覆蓋,所以您的屬性不會被其繼承。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.