simon of earth
simon of earth

Reputation: 129

Get ModelMetadata for a class in .NET Core

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?

Upvotes: 6

Views: 9308

Answers (2)

tnJed
tnJed

Reputation: 917

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.

Upvotes: 8

Ilya Chumakov
Ilya Chumakov

Reputation: 25039

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));
}

Upvotes: 5

Related Questions