Get ModelMetadata for a class in .NET Core
Asked Answered
S

2

6

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?

Selda answered 30/3, 2017 at 20:46 Comment(0)
C
8

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.

Casia answered 11/12, 2019 at 22:10 Comment(0)
R
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));
}
Redtop answered 10/4, 2017 at 19:48 Comment(1)
Not sure what the case was at the time of this answer but IModelMetadataProvider MetadataProvider is now a property of ControllerBase.Curly

© 2022 - 2024 — McMap. All rights reserved.