Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 352
Diego Rafael Souza Avatar asked Aug 17 '18 16:08

Diego Rafael Souza


People also ask

What is Fluent API configuration?

Fluent API is an advanced way of specifying model configuration that covers everything that data annotations can do in addition to some more advanced configuration not possible with data annotations.

What is Entity Framework Fluent API?

Entity Framework Fluent API is used to configure domain classes to override conventions. EF Fluent API is based on a Fluent API design pattern (a.k.a Fluent Interface) where the result is formulated by method chaining. In Entity Framework Core, the ModelBuilder class acts as a Fluent API.

How do you configure a primary key for an entity in Entity Framework Fluent API?

Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.

What is OnModelCreating method?

The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.


1 Answers

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();
like image 59
Reza Aghaei Avatar answered Oct 19 '22 07:10

Reza Aghaei