【发布时间】:2020-10-08 02:34:33
【问题描述】:
我正在使用带有反射的 Entity Framework Core 来动态生成一些表单。除 WHERE 子句外,一切正常。我收到以下错误:
表达式树可能不包含动态操作
我可以通过将 IQueryable 转换为 List 来解决此问题,但这会引入我想避免的不同问题。
这是我的代码:
public async void ViewCollection(PropertyInfo propertyInfo)
{
Type propertyType = propertyInfo.PropertyType;
InversePropertyAttribute inversePropertyAttribute = (InversePropertyAttribute)ReflectionHelpers.GetAttribute(propertyInfo, typeof(InversePropertyAttribute));
//GET THE TYPE OF THE COLLECTION
Type collectionType = propertyInfo.PropertyType.GenericTypeArguments[0];
//GET THE INVERSE PROPERTY INFO
PropertyInfo inverseProperty = collectionType.GetProperty(inversePropertyAttribute.Property);
//GET THE FOREIGN KEY ATTRIBUTE FROM THE INVERSE PROPERTY
ForeignKeyAttribute foreignKeyAttribute = (ForeignKeyAttribute)ReflectionHelpers.GetAttribute(inverseProperty, typeof(ForeignKeyAttribute));
//GET THE FOREIGN KEY PROPERTY FROM THE FOREIGN KEY ATTRIBUTE
PropertyInfo foreignKeyProperty = collectionType.GetProperty(foreignKeyAttribute.Name);
//GET INCLUDED TYPE NAMES BY FOREIGN KEY
IEnumerable<string> includedTypes = collectionType.GetProperties().Where(p => p.PropertyType.IsClass).Where(p => ReflectionHelpers.HasAttribute(p, typeof(ForeignKeyAttribute))).Select(r => r.Name);
//GET THE DATA SET
IQueryable<dynamic> items = ReflectionHelpers.GetDbCollectionByType(Db, collectionType);
//INCLUDE THE INCLUDED TYPES BY NAME
foreach (string includedType in includedTypes) items = items.Include(includedType);
//THIS IS WHERE THE ERROR IS
items = items.Where(i => foreignKeyProperty.GetValue(i, null) == PrimaryKeyProperty.GetValue(Item, null));
await ShowCollection(collectionType, items, propertyInfo.Name);
}
如何在不将类型更改为列表的情况下解决此问题?
【问题讨论】:
标签: c# sql dynamic reflection entity-framework-core