简体   繁体   中英

How to retrieve Entity Configuration from Fluent Api

Using Entity-Framework 6 I'm able to set up the configuration through Fluent Api like this:

public class ApplicationUserConfiguration : EntityTypeConfiguration<ApplicationUser>
{
    public ApplicationUserConfiguration()
    {
        this.HasKey(d => d.Id);
        this.Ignore(d => d.UserId);
    }
}

Source from this question

Using the attribute approach I'm able to know what's the property roles by reflection, but I wonder how can I retrieve these configurations, like Key for example, with Fluent Api approach?

There's no public property from the EntityTypeConfiguration<> class.

Is that possible to get the Key and ForeignKey somehow?

There is a MetadataWorkspace class which provides API to retrieve metadata about storage, model, CLR types and mappings for Entity Framework.

Represents the ADO.NET metadata runtime service component that provides support for retrieving metadata from various sources.

Having an instance of DbContext , you can find its MetadataWorkspace using following code:

var metadataWorkspace = ((IObjectContextAdapter)dbContext).ObjectContext.MetadataWorkspace;

Then you can get item collections which contain different types of models including object model, the conceptual model, the storage (database) model, and the mapping model between the conceptual and storage models.

The following extension methods returns EntityType for given clr type:

using System;
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Linq;

public static class DbContextExtensions
{
    public static EntityType GetEntityMetadata<TEntity>(this DbContext dbContext)
    {
        if (dbContext == null)
            throw new ArgumentNullException(nameof(dbContext));

        var metadataWorkspace = ((IObjectContextAdapter)dbContext)
            .ObjectContext.MetadataWorkspace;
        var itemCollection = ((ObjectItemCollection)metadataWorkspace
            .GetItemCollection(DataSpace.OSpace));
        var entityType = metadataWorkspace.GetItems<EntityType>(DataSpace.OSpace)
            .Where(e => itemCollection.GetClrType(e) == typeof(TEntity)).FirstOrDefault();

        if (entityType == null)
            throw new Exception($"No entity mapped to CLR type '{typeof(TEntity)}'.");

        return entityType;
    }
}

Then you can use EntityType to extract more information about the model, for example you can find a list of key properties:

var keys = dbcontext.GetEntityMetadata<Category>().KeyProperties.Select(x=>x.Name).ToList();

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