gpt4 book ai didi

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

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

我在每次数据库命中后手动使用 .Select(i=> new T{...}) 将我的实体对象转换为 DTO 对象。以下是一些示例实体和 DTOS

用户实体;

public partial class User
{
public int Id { get; set; }
public string Username { get; set; }
public virtual UserEx UserEx { get; set; }
}

用户DTO;

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

UserEx实体;

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

UserEx DTO;

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

我的转化表达方式;

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
};
}
}

以及我目前对 UserDTO 的使用情况;

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

对于 UserExDTO;

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

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

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()
};
}

有什么办法可以做到这一点,还是我应该写下与类似需求无关的每个表达方式?

最佳答案

我只用 NeinLinq 就解决了我的问题,而且不止于此。这是我的解决方案;您需要先删除嵌套声明。

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

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

public static Expression<Func<UserEx, UserExDTO>> GetUserExDtOCompbinedExpression()
{
//Translate() and To() methods do all the job
return GetUserDTOConversionExpression().Translate()
.To(userEx => userEx.User, userExDTO => userExDTO.UserModel, GetUserExDTOConversionExpression());
}

关于c# - Linq.Select() 中的嵌套表达式方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50058694/

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