tags:

views:

244

answers:

1

I am writing a small code generator which would read into an edmx file and create business objects on the base of a template. I am using reflection to spit out the type names.

The problem is when I encounter a property (PropertyInfo) of type Entity Reference, (basically an entity property if there is a referential integrity), the PropertyInfo.PropertyType.Name comes as "EntityReference`1" which is not recognized by the compiler.

PropertyInfo.PropertyType.FullName gives "System.Data.Objects.DataClasses.EntityReference`1[[BusinessObjectGenerator.Models.BE_Additional_Info, BusinessObjectGenerator, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]", which is also not recognized by the C# compiler.

Now I faced the same problem with the Nullable types. And I found the static method Nullable.GetUnderlyingType(type) which solved the issue. How do I get the name of type of a property that is an entity type, a name that the C# compiler recognizes?

A: 

Generic types contain ` in their Name. To get the C# readable name of the type, you will need to first check if it is a generic type using Type.IsGenericType. If it is a generic type, then you can use Type.GetGenericArguments() to get the list of type arguments to the generic type. By getting their names, you can put together the generic type name like. For example, if the type is

Dictionary<int, string>

Then, the type name would actually be Dictionary`2. Using GetGenericArguments would return an array with two types (int, and string). From these you can generate the composite name.

Note: Each of the types returned from GetGenericArguments() may itself be a generic type, so you should write this as a recursive algorithm.

Tarydon