将 Expression> 谓词转换为 Expression> 谓词

2024-04-14

我的表达有问题

我有一个实体

public class User{ 
public string Username{get;set;}
  public int PhoneNumber{get;set;}
  public string FIrstName{get;set;}
  public string LastName{get;set;}
}

我有一个 DTO

public class DTOUser{
  public string Username{get;set;}
  public int PhoneNumber{get;set;}
  public string FIrstName{get;set;}
  public string LastName{get;set;}
  }

然后我有一个通用的代码片段

 public IList<DTOUser> SelectAll(Expression<Func<DTOUser, bool>> predicate)
    {
           using (var adc = _conn.GetContext())
        {   
       // what should I do ?? so i can convert Predciate to get all values from Users (Entity)   
//it generates an error because predicate can't be cast into Entity User                    
 //   var users = adc.Users.All(predicate);
       }          
    }

我想通过传递 LAMBDA 表达式来获取 DTOUser 列表

accountrepo.SelectAll( user => user.firstname.equals ("sample"));

我研究了这个问题并得出结论,因为 DTOUser 和 User 是不同的类型,所以很难将表达式从一种类型转换为另一种类型。

Jon Skeet 提出了一种解决方案:

如何将 Expression> 转换为 Expression> https://stackoverflow.com/questions/729295/how-to-cast-expressionfunct-datetime-to-expressionfunct-object

但由于这个解决方案似乎我必须将每个值从 DTOUser 映射到 User,这不会使它变得更复杂,因为我的 DTOUser 包含超过 15 个属性。

有人可以帮我吗?


您不能直接从一种类型转换为另一种类型,您可以这样做:

  1. 手动映射
  2. 使用反射自动映射(因为属性名称相同)
  3. Use 自动映射器 http://automapper.codeplex.com/

对于使用反射的映射,您可以使用以下通用代码:

public static T1 CopyProperties<T1, T2>(T2 model)
    where T1 : new()
    where T2 : new()
{
    // Get all the properties in the model
    var type = model.GetType();
    var properties = type.GetProperties();

    var result = new T1();
    var resultType = result.GetType();
    var resultProperties = resultType.GetProperties();

    // Loop through each property
    foreach (var property in properties)
    {
        var resultProperty = resultProperties.FirstOrDefault(n => n.Name == property.Name && n.PropertyType == property.PropertyType);
        if (resultProperty != null)
        {
            resultProperty.SetValue(result, property.GetValue(model, null), null);
        }
    }
    return result;
}

它将复制具有相同类型和名称的属性

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 Expression> 谓词转换为 Expression> 谓词 的相关文章

随机推荐