How to create CodeFunction2 with IEnumerable<> Type?
-
20-09-2019 - |
Question
I really need to create something like the following, I am building 2 classes, the first is a class with the name of tableNameAsSingular (i.e AddressEntity) , in my second worker class I need to having something like the following
public IEnumerable<AddressEntity> GetAddressEntity()
{
// the good stuff...
}
When creating the Function I have the following..
Type t = Type.GetType("IEnumerable<" + tableNameAsSingular + ">");
CodeFunction2 finderFunction = (CodeFunction2)entityServiceClass.AddFunction("Get" + table.Name, vsCMFunction.vsCMFunctionFunction, t, -1, vsCMAccess.vsCMAccessPublic, null);
but t is always null
When I do Type.GetType(tableNameAsSingular)
it returns null too
Any help or pointers would be greatfully received. Also if anyone knows where a plethora of EnvDTE code generation knowledge lives I would be sooo greatful!
Update
I have now tried it just as a string using the following:
public void AddFinderMethod()
{
string t = "IEnumerable<" + tableNameAsSingular + ">";
CodeFunction2 finderFunction = (CodeFunction2)entityServiceClass.AddFunction("Get" + table.Name, vsCMFunction.vsCMFunctionFunction, t, -1, vsCMAccess.vsCMAccessPublic, null);
// Code here remove as it does not get this far yet.
}
but I get "IEnumerable<ProductEntity> is not a valid identifier
" error message in the AddFunction Method
Solution 2
have managed to get it working with the following:
string returnType = "System.Collections.Generic.IEnumerable<" + tableNameAsSingular + ">";
CodeFunction2 finderFunction = (CodeFunction2)entityServiceClass.AddFunction("Get" + table.Name, vsCMFunction.vsCMFunctionFunction, returnType, -1, vsCMAccess.vsCMAccessPublic, null);
OTHER TIPS
The syntax IEnumerable<T>
is C# syntax, not .NET syntax (which uses back-ticks, counters, etc). What you mean is:
Type tableType = Type.GetType(assemblyQualifiedNameToEntity);
Type enumerableType = typeof(IEnumerable<T>).MakeGenericType(tableType);
Note that Assembly.GetType
is usually a better choice, as you can just use namespace-qualified names:
Assembly asm = typeof(SomeKnownType).Assembly;
Type tableType = asm.GetType(namespaceQualifiedNameToEntity);