gpt4 book ai didi

c# - 如何使用反射来调用 DbModelBuilder.Entity.Ignore(x => x.Property)?

转载 作者:太空宇宙 更新时间:2023-11-03 13:47:21 24 4
gpt4 key购买 nike

我正在基于我的 poco 类上的属性动态执行流畅的映射,我的 .Property 案例工作正常,但在尝试运行 .Ignore() 方法时失败了:

private void AddEntities(DbModelBuilder modelBuilder)
{
var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
foreach (var entityType in EntityBaseTypes)
{
dynamic entityConfiguration = entityMethod.MakeGenericMethod(entityType).Invoke(modelBuilder, new object[] { });
foreach (PropertyInfo propertyInfo in entityType.GetProperties().Where(x => x.CanWrite))
{

foreach (var attribute in propertyInfo.GetCustomAttributes())
{
LambdaExpression propertyLambda = PropertyGetLambda(entityType, propertyInfo.Name, typeof(string));
string attributeName = attribute.GetType().Name;
if (attributeName == "NotMappedAttribute")
{
MethodInfo ignoreMethod = (MethodInfo)entityConfiguration.GetType().GetMethod("Ignore");
//BLOWS UP HERE: Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true
ignoreMethod.Invoke(entityConfiguration, new[] { propertyLambda });

}
else if (attributeName == "ColumnAttribute")
{
dynamic column = attribute;
var propertyMethod = entityConfiguration.GetType().GetMethod("Property", new Type[] { propertyLambda.GetType() });
var entityProperty = (PrimitivePropertyConfiguration)propertyMethod.Invoke(entityConfiguration, new[] { propertyLambda });
//WORKS FINE:
entityProperty.HasColumnName(column.Name);
}
}
}

}
}

我认为 .Ignore() 方法参数所需的类型不同。这是我试图调用的方法:.Ignore()

public void Ignore<TProperty>(
Expression<Func<TStructuralType, TProperty>> propertyExpression
)

最佳答案

我认为您需要使用以下方法获取 Ignore 方法的 MemberInfo:

MethodInfo ignoreMethod = typeof(StructuralTypeConfiguration<>)
.MakeGenericType(entityType)
.GetMethod("Ignore")
.MakeGenericMethod(propertyInfo.PropertyType);

Ignore 是一种方法,其通用参数对应于 Expression 的属性类型,因此您需要在尝试调用它之前提供属性类型。

关于c# - 如何使用反射来调用 DbModelBuilder.Entity<T>.Ignore(x => x.Property)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14843462/

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