简体   繁体   中英

How to access properties of entities in EF Core dynamically?

I have a base DatabaseContext that inherits from DbContext . I'm trying to configure some properties of my entity models centrally.

Here's my code of DatabbaseContext :

using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace Company.DataAccess
{
    public abstract class DatabaseContext : DbContext
    {
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var allEntities = modelBuilder.Model.GetEntityTypes().Select(p => modelBuilder.Entity(p.ClrType));

            foreach (var entity in allEntities)
            {
                // var properties = entity.GetProperties(); // this line throws exception
                // foreach (var property in properties)
                // {
                //  // if it's Guid, configure it this way
                //  // if it's Enum, configure it this way
                //  // if it's Date, configure it this way
                //  // ...
                // }
            }
        }
    }
}

But the line of entity.GetProperties() throws this error:

DatabaseContext.cs: error CS1061: 'EntityTypeBuilder' does not contain a definition for 'GetProperties' and no accessible extension method 'GetProperties' accepting a first argument of type 'EntityTypeBuilder' could be found (are you missing a using directive or an assembly reference?)

How can I get properties of my entity models?

As the error suggests GetProperties is not available on type EntityTypeBuilder . So you won't be able to call it. But EntityTypeBuilder as property Metadata on which you can call GetProperties . So try below -

entity.Metadata.GetProperties();

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