gpt4 book ai didi

c# - 为 Entity Framework CPT5 构建 EntityTypeConfiguration 列表的反射(reflection)

转载 作者:太空狗 更新时间:2023-10-29 21:03:10 27 4
gpt4 key购买 nike

我不想手动将每个映射类添加到 ModelBuilder(),因此尝试使用我有限的反射知识来注册它们。这就是我所拥有的,这是我得到的错误:

代码:

private static ModelBuilder CreateBuilder() {
var contextBuilder = new ModelBuilder();
IEnumerable<Type> configurationTypes = typeof(DatabaseFactory)
.Assembly
.GetTypes()
.Where(type => type.IsPublic && type.IsClass && !type.IsAbstract && !type.IsGenericType && typeof(EntityTypeConfiguration).IsAssignableFrom(type) && (type.GetConstructor(Type.EmptyTypes) != null));

foreach (var configuration in configurationTypes.Select(type => (EntityTypeConfiguration)Activator.CreateInstance(type)))
{
contextBuilder.Configurations.Add(configuration);
}

return contextBuilder;
}

错误:错误 2 无法从用法中推断方法“System.Data.Entity.ModelConfiguration.Configuration.ConfigurationRegistrar.Add(System.Data.Entity.ModelConfiguration.EntityTypeConfiguration)”的类型参数。尝试明确指定类型参数。 C:\root\development\playground\PostHopeProject\PostHope.Infrastructure.DataAccess\DatabaseFactory.cs 67 17 PostHope.Infrastructure.DataAccess

最佳答案

原答案:

http://areaofinterest.wordpress.com/2010/12/08/dynamically-load-entity-configurations-in-ef-codefirst-ctp5/

隐含解决方案的详细信息:

上面引用的文章表明,您可以使用 dynamic 关键字绕过编译时类型检查,从而绕过尝试将配置添加到通用 Add()< 的限制 DbModelBuilder 的方法。这是一个快速示例:

// Load all EntityTypeConfiguration<T> from current assembly and add to configurations
var mapTypes = from t in typeof(LngDbContext).Assembly.GetTypes()
where t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>)
select t;

foreach (var mapType in mapTypes)
{
// note: "dynamic" is a nifty piece of work which bypasses compile time type checking... (urgh??)
// Check out: http://msdn.microsoft.com/en-us/library/vstudio/dd264741%28v=vs.100%29.aspx
dynamic mapInstance = Activator.CreateInstance(mapType);
modelBuilder.Configurations.Add(mapInstance);
}

您可以阅读有关使用此关键字的更多信息 on MSDN

关于c# - 为 Entity Framework CPT5 构建 EntityTypeConfiguration 列表的反射(reflection),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4383024/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com