I am using Entity Framework. I am generating both my entities and contexts dynamically with CodeDOM (one context for every entity type until I get into complex entity relationships). In order to make sure the entity I generate is part of the model of its corresponding context, I am using reflection to get the entity's type and I write this into the code that generates the context. To see this more concretely, I have this method in my class that generates the context:
public static CodeMemberProperty HardCodeDbSet(string contextName, Type entityType)
{
string entityName = entityType.ToString();
CodeMemberProperty prop = new CodeMemberProperty();
prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
prop.Name = entityName + "s";
prop.Type = new CodeTypeReference(typeof(DbSet<>).MakeGenericType(entityType));
return prop;
}
This methods generates the following line in the generated context class:
public System.Data.Entity.DbSet<Models.GeneratedEntities.Soap> Soaps
{
}
It says Soap and Soaps because in my test program I made the entity name Soap (just something random). But in general it will be whatever entity name I give it.
When I try to generate an instance of this class to use, however, I get the following error:
"c:\Users\MyUserAccount\Documents\ContextTest\bin\Debug\EFEntityTest_v1.cs(29,94) : error CS0234: The type or namespace name 'Soap' does not exist in the namespace 'Models.GeneratedEntities' (are you missing an assembly reference?)\n"
Line 29, column 94 is exactly where Soap starts in the line after GeneratedEntities.:
public System.Data.Entity.DbSet<Models.GeneratedEntities.Soap> Soaps
{
}
So clearly this line isn't working properly:
prop.Type = new CodeTypeReference(typeof(DbSet<>).MakeGenericType(entityType));
I know it has something to do with the fact that I'm calling MakeGenericType on something that's also generated dynamically with CodeDOM, but I feel like it should work. Does anyone have any ideas of what's going on? Also I do have the reference assembly passed in for the project where Models.GeneratedEntities is.
Aucun commentaire:
Enregistrer un commentaire