Linq.Select()中的嵌套表达式方法调用

时间:2018-04-27 08:50:23

标签: c# linq lambda expression entity-framework-core

我在手动每次db命中后使用public partial class User { public int Id { get; set; } public string Username { get; set; } public virtual UserEx UserEx { get; set; } } 将我的实体对象转换为DTO对象。以下是一些示例实体和DTOS

用户实体;

public class UserDTO
{
    public int Id { get; set; }
    public string Username { get; set; }
}

用户DTO;

public class UserEx
{
    public int UserId { get; set; }
    public string MyProperty1 { get; set; }
    public virtual User User { get; set; }
}

UserEx实体;

public class UserExDTO
{
    public int MyProperty1 { get; set; }
    public UserDTO UserModel { get; set; }
}

UserEx DTO;

public static class ConversionExpression
{
    public static Expression<Func<UserEx, UserExDTO>> GetUserExDTOConversionExpression()
    {
        return userEx => new UserExDTO
        {
            MyProperty1 = userEx.MyProperty1,
            UserModel = new UserDTO
            {
                Id = userEx.User.Id,
                Username = userEx.User.Username
            }
        };
    }

    public static Expression<Func<User, UserDTO>> GetUserDTOConversionExpression()
    {
        return user => new UserDTO
        {
            Id = user.Id,
            Username = user.Username
        };
    }
}

我的转换表达方法;

myContext.Users
    .Select(ConversionExpression.GetUserDTOConversionExpression())
    .ToList();

我目前使用UserDTO;

myContext.UserExes
    .Select(ConversionExpression.GetUserExDTOConversionExpression())
    .ToList();

用于UserExDTO;

new UserDTO
{
    Id = userEx.User.Id,
    Username = userEx.User.Username
}

为长期介绍道歉,现在这是我的问题; 我需要分组

public static Expression<Func<UserEx, UserExDTO>> GetUserExDTOConversionExpression()
{
    return userEx => new UserExDTO
    {
        MyProperty1 = userEx.MyProperty1,
        //this line does not behave like the other one 
        UserModel = userEx.User.GetUserDTOConversionExpression()
    };
}

由于单点担忧。所以我想要这样的东西;

filteredprovince

有没有办法做到这一点,还是应该记下每个表达个人而且与相似需求无关?

1 个答案:

答案 0 :(得分:0)

除了NeinLinq,我已经解决了自己的问题。这是我的解决方案; 您需要先删除嵌套的声明。

{ ... }

然后使用NeinLinq的To方法定义翻译;

public static Expression<Func<UserEx, UserExDTO>> GetUserExDTOConversionExpression()
{
    return userEx => new UserExDTO
    {
        MyProperty1 = userEx.MyProperty1
        //We removed other model declaration here.
    };
}