简体   繁体   中英

DBSet dynamically register using interface

I want to create a code block which register DBsets dynamically. I decide to use an empty Interface to catch classes which implement the interface.

Here is my code block.

 var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                var entityTypes = assembly
                    .GetTypes()
                    .Where(t =>
                        t.GetInterfaces().Contains(typeof(IBaseEnt))).toList();            

                foreach (var type in entityTypes)
                {
                    entityMethod.MakeGenericMethod(type)
                      .Invoke(modelBuilder,  null);
                }
            }

But my seed methods can't handle my dbsets. Please help me.

I also tried this code block.

var entityTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                                  where t.GetInterfaces().Contains(typeof(IBaseEnt))
                                           && t.GetConstructor(Type.EmptyTypes) != null
                                  select t;

Here is the solution. It is working on EF 6.1.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                var entityTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                                  where t.GetInterfaces().Contains(typeof(IBaseEnt))
                                           && t.GetConstructor(Type.EmptyTypes) != null
                                  select t;

                foreach (var type in entityTypes)
                {
                    entityMethod.MakeGenericMethod(type)
                      .Invoke(modelBuilder, null);
                }
            }
            base.OnModelCreating(modelBuilder);
        }

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