簡體   English   中英

如何獲得外鍵上的“ NameOf”?

[英]How do I get the “NameOf” on a Foreign Key?

嘗試提取外鍵屬性中包含的屬性的屬性時遇到麻煩。 為了說明這一點,我在某些課程中有這些屬性

[Required(ErrorMessage = "Please enter value.")]
public long ObjectCatalogId{ get; set; }

[ForeignKey(nameof(ObjectCatalogId))]
public ObjectCatalog ObjectCatalog { get; set; }

我想找到一種通過查看ObjectCatalog屬性上的屬性來獲取ObjectCatalogId屬性上的屬性的方法。 我希望這將意味着提取外鍵的名稱(即ObjectCatalogId),然后在類ObjectCatalogId和ObjectCatalog中找到該屬性,並使用反射來獲取屬性。

我的問題是如何在外鍵上獲取名稱?

 attribute.GetType().Name

不起作用 此外,是否有更有效的方法來實現這一目標?

問題是,當我從屬性中獲取屬性時,將其視為Attribute而不是ForeignKeyAttribute。 所以當我改變

Attribute attribute =  Property.GetCustomAttribute(typeof(ForeignKeyAttribute));

ForeignKeyAttribute attribute = (ForeignKeyAttribute) Property.GetCustomAttribute(typeof(ForeignKeyAttribute));

我只用一個名字就得到了想要的名字

string name = attribute.Name;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM