gpt4 book ai didi

c# - 如何在 Expression 中转换可以是对象或 List 的 TResult?
转载 作者:行者123 更新时间:2023-12-05 03:17:45 29 4
gpt4 key购买 nike

正如标题所说,“如何将 TResult 转换为 objectList<object>Expression<Func<T,TResult?> 中?”

    public Task ExplicitLoadAsync<TProperty>(T entity, Expression<Func<T, TProperty?>> propertyExpression) where TProperty : class
{
var typeOfProp = typeof(TProperty);
if (typeOfProp.IsInterface && typeOfProp.GetGenericTypeDefinition() == typeof(ICollection<>))
{
var collectionExpression = propertyExpression as Expression<Func<T, IEnumerable<TProperty>>>;
if (collectionExpression is not null)
{
return _dbContext.Entry(entity).Collection(collectionExpression).LoadAsync();
}
}

return _dbContext.Entry(entity).Reference(propertyExpression).LoadAsync();
}

collectionExpression将始终为空,问题是 Reference()只接受IEnumerable<TProperty>并且重载是不可能的,因为它将始终使用 TProperty 的方法而不是 Expression<Func<T, IEnumerable<TProperty>>> propertyExpression

原因是转换错误,因为它将是 IEnumerable<IEnumerable<...>>如何解决?

一种方法是使用两个不同名称的方法,但我想跳过它,因为这需要在整个代码库中进行更多重构。

最佳答案

此解决方案基于 Guru Stron's deleted answer

public async Task ExplicitLoadAsync<T, TProperty>(T entity, Expression<Func<T, IEnumerable<TProperty>>> propertiesExpression) where T : class where TProperty : class
=> await _dbContext.Entry(entity).Collection(propertiesExpression).LoadAsync();

public async Task ExplicitLoadAsync<T, TProperty>(T entity, Expression<Func<T, TProperty?>> propertyExpression) where T : class where TProperty : class
=> await _dbContext.Entry(entity).Reference(propertyExpression).LoadAsync();

这里的技巧是使用不同的参数名称:

  • Expression<Func<T, IEnumerable<TProperty>>> propertiesExpression
  • Expression<Func<T, TProperty?>> propertyExpression

这使您能够调用两个重载

ExplicitLoadAsync<Entity, string>(enity, e => e.SingleString);
ExplicitLoadAsync<Entity, string>(enity, propertiesExpression: e => e.CollectionOfStrings);

关于c# - 如何在 Expression<Func<T,TResult?> 中转换可以是对象或 List<object> 的 TResult?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73984087/

29 4 0