Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何为我的服务实现DTO?_C#_Asp.net Core_.net Core - Fatal编程技术网

C# 如何为我的服务实现DTO?

C# 如何为我的服务实现DTO?,c#,asp.net-core,.net-core,C#,Asp.net Core,.net Core,目前,我不得不选择模特。一个用户模型用于存储密码,另一个用户模型用于隐藏密码字段 public class User { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } public string UserName { get; set; } public string Password { ge

目前,我不得不选择模特。一个用户模型用于存储密码,另一个用户模型用于隐藏密码字段

public class User
    {

        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        [JsonIgnore]
        public string Email { get; set; }
    }
现在,在连接到mongoDB的服务中,我想将模型更改为DTO版本

服务:

public List<User> Get() => _users.Find(user => true).ToList();
public ActionResult<List<User>> Get() => _userService.Get();
public List Get()=>\u users.Find(user=>true.ToList();
我应该如何处理这个问题?或者我应该在控制器上进行更改

控制器:

public List<User> Get() => _users.Find(user => true).ToList();
public ActionResult<List<User>> Get() => _userService.Get();
public ActionResult Get()=>\u userService.Get();

您可以从服务和控制器返回UserDTO

服务:

public List<UserDTO> Get() => _users.Where(user => true).Select(x=> new UserDTO{
   UserName = x.UserName,
   ....
}).ToList();
public List Get()=>\u users.Where(user=>true)。选择(x=>new UserDTO{
UserName=x.UserName,
....
}).ToList();
控制器:

   public ActionResult<List<UserDTO>> Get() => _userService.Get();
public ActionResult Get()=>\u userService.Get();
您可以使用AutoMapper进行映射,而不是使用
Select
方法


最后一点我想提到的是,您应该从控制器返回UserDTO,但不必从服务返回dto。这是一种体系结构方法,您也可以映射到控制器。

这听起来像是映射库的工作。就我个人而言,我使用。要使用它,请安装NuGet软件包并创建映射配置文件类:

public class MyProfile : Profile
{
    public MyProfile()
    {
        CreateMap<User, UserDTO>();
    }
}
AddAutoMapper
方法还有其他重载。这个类发现从提供的程序集中的
Profile
继承的所有类

var services = new ServiceCollection().AddAutoMapper(typeof(Program).Assembly);