burke
burke

Reputation: 81

How do I get the "NameOf" on a Foreign Key?

I am running into difficulties when trying to extract the attributes of a property contained in a foreign key attribute. To illustrate, I have these properties in some class

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

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

I want to find a way to get attributes on ObjectCatalogId property by looking at attributes on ObjectCatalog property. I expect this would mean extracting the name of the Foreign Key (which is ObjectCatalogId), then finding that property in the class ObjectCatalogId and ObjectCatalog both live in and using reflection to get the attributes.

My question is how do I get the name on the Foreign Key?

 attribute.GetType().Name

Doesn't work. Additionally, are there more efficient ways of accomplishing this?

Upvotes: 2

Views: 2249

Answers (1)

burke
burke

Reputation: 81

The problem was that when I got an attribute from my property I treated it as Attribute instead of ForeignKeyAttribute. So when I changed

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

to

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

I got the name I wanted by just using

string name = attribute.Name;

Upvotes: 3

Related Questions