5

In Entity Framework 6 I could get the ModelMetadata for a class (myModel) like this:

var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, myModel.GetType());

How can I do the same in .net core 1.1.1?

Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114
simon of earth
  • 119
  • 1
  • 6

2 Answers2

6

In ASP.NET Core 3.0 there's EmptyModelMetadataProvider class which implements DefaultModelMetadataProvider which implements ModelMetadataProvider which is abstract. We are able to simply instantiate EmptyModelMetadataProvider and call GetMetadataForType(typeof(MyModel)) and it will return the required metadata. My particular use for this answer is testing a custom model binder.

tnJed
  • 838
  • 9
  • 12
5

ModelMetadataProvider is an ASP.NET feature and it has nothing to do with Entity Framework. In ASP.NET Core you may easily inject a default IModelMetadataProvider implementation using the built-in DI:

public FooController(IModelMetadataProvider provider) 
{
    var metadata = provider.GetMetadataForType(typeof(model));
}
Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114
  • 1
    Not sure what the case was at the time of this answer but `IModelMetadataProvider MetadataProvider` is now a property of `ControllerBase`. – Aidan Ryan Mar 11 '19 at 20:30