Reza Yousefi
Reza Yousefi

Reputation: 162

Fill modelBuilder.Entity with dynamic values in dbcontext

enter image description hereI have a lot of views and I have to use(in OnModelCreating asp.net core 5)

modelBuilder.Entity <y1> (). HasNoKey (). ToView (null); 
... 
modelBuilder.Entity <yn> (). HasNoKey (). ToView (null);

Is there a way to dynamically set Entity values?

modelBuilder.Entity <MyClass1> (). HasNoKey (). ToView (null); 
... 
modelBuilder.Entity <MyClassn> (). HasNoKey (). ToView (null);

I tried several ways but got the following error =>y1 is type but used like variable

get items => foreach (var entity in modelBuilder.Model.GetRootEntityTypes())

Upvotes: 0

Views: 1554

Answers (2)

Juanma Feliu
Juanma Feliu

Reputation: 1346

I suppouse you are using EF 5.0, have you tried using Shared-Type Entity Types?

EF Core 5.0 allows the same CLR type to be mapped to multiple different entity types; such types are known as shared-type entity types. While any CLR type can be used with this feature, .NET Dictionary offers a particularly compelling use-case which we call "property bags":

public class ProductsContext : DbContext
{
    public DbSet<Dictionary<string, object>> Products => Set<Dictionary<string, object>>("Product");

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.SharedTypeEntity<Dictionary<string, object>>("Product", b =>
        {
            b.IndexerProperty<int>("Id");
            b.IndexerProperty<string>("Name").IsRequired();
            b.IndexerProperty<decimal>("Price");
        });
    }
}

Update: TEntity is a class not a Type. I haven't tested but maybe this can shed some light:

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            foreach (var eType in modelBuilder.Model.GetEntityTypes())
            {
                EntityTypeBuilder x = modelBuilder.SharedTypeEntity<Dictionary<string, object>>(eType.Name, b =>
                {
                    foreach (var p in eType.GetProperties())
                    {
                        if(p.GetType() == typeof(int))
                        {
                            b.IndexerProperty<int>(p.Name);
                        }
                        else if(p.GetType() == typeof(string))
                        {
                            b.IndexerProperty<string>(p.Name);
                        }
                        
                    }
                   
                }).SharedTypeEntity(eType.Name, eType.GetType());

                x.HasNoKey();

            }
        }

Upvotes: 1

Reza Yousefi
Reza Yousefi

Reputation: 162

foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
    modelBuilder.Entity(entity.ClrType).HasNoKey().ToView(null);
}

Upvotes: 0

Related Questions