Reputation: 2229
I'd like to use OData 4 along with WebApi2 and EF, where as for the latter I got about 30 model configuration classes. Now, since OData requires an EDM model, I would like to somehow reuse my existing model configuration - or at least put the configuration classes into a different library to keep my web api configuration manageable.
I tried creating EDM entity type configuration classes using EntitySetConfiguration<'1>
, however the constructor of that class is internal. So - is there a way to automatically build an EDM model using a DbContext
during runtime or create separate configuration classes?
Upvotes: 1
Views: 1009
Reputation: 436
You can build an edm model using a DBContext via reflection.
public static void Register(HttpConfiguration config)
{
var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.ContainerName = "EntityContainer";
using(var ctx = new MyDBContext())
{
var dbSets = ctx.GetType().GetProperties();
foreach(var set in dbSets)
{
if(set.PropertyType.IsGenericType)
{
method = entitySet.MakeGenericMethod(set.PropertyType.GenericTypeArguments[0]);
bool containsEntity = false;
foreach (var entity in modelBuilder.EntitySets)
{
if (entity.GetType().Equals(set.PropertyType.GenericTypeArguments[0]))
containsEntity = true;
if (!containsEntity)
method.Invoke(modelBuilder, new[] { set.Name });
}
}
}
}
_config.MapODataServiceRoute(
routeName: "entities",
routePrefix: API_ENTITIES_BASE_URI,
model: modelBuilder.GetEdmModel()
);
}
Hope it helps.
Upvotes: 2