How to retrieve Entity Configuration from Fluent Api

.net c# ef-fluent-api entity-framework entity-framework-6

Question

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?

1
10
12/19/2019 5:49:44 PM

Accepted Answer

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();
8
10/7/2019 10:14:02 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow