问题描述
类似这样publicclassDefaultDBContext:DBContext{publicDbSet<User>User{get;set;}..........}
需要动态增加类似这个user的entity我现在只知道它的type的string;想用dbcontext读取这个未知实体的数据,有什么思路吗
解决方案
解决方案二:
参考DbSet<MyEntity>set=context.Set<MyEntity>();
或DbSetset=context.Set(typeof(MyEntity));
或者利用反射,通过实现DbContext的OnModelCreating方法,参考引用
However,foraprojectwithevenafairbitofdomaincomplexity,definingDbSetpropertiesforallentitieswouldnotbepossibleandweneedawaytodynamicallyreadourEntityTypesandaddthemdynamicallyintheDbContext.ThiscanbeachievedbyimplementingOnModelCreatingmethodoftheDbContext.TheEntityTypescanbereadfromeithertheexecutingassemblyAssembly.GetExecutingAssembly()orbyloadingmorethanoneassemblieswhichcanbeplacedinaconfigurationfile(asshownbelowintheexample).FordetailsaboutsettingupthecustomconfigurationsectionwithyourassembliesseemylastpostThefollowingcodewilladdallClassTypestotheDbContextforalltheassembliesaddedintheconfigurationfile,noticeweareactuallycallingmodelBuilder.Entity<T>()methodthroughreflection.
publicclassMyAppContext:DbContext{protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){CustomAssemblySectionconfigSection=(CustomAssemblySection)System.Configuration.ConfigurationManager.GetSection("CustomAssemblySection");foreach(CustomAssemblycustomAssemblyinconfigSection.Assemblies){Assemblyassembly=Assembly.Load(customAssembly.Name);foreach(Typetypeinassembly.ExportedTypes){if(type.IsClass){MethodInfomethod=modelBuilder.GetType().GetMethod("Entity");method=method.MakeGenericMethod(newType[]{type});method.Invoke(modelBuilder,null);}}}base.OnModelCreating(modelBuilder);}}