简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM