gpt4 book ai didi

C# WebApi重构选择Linq

转载 作者:行者123 更新时间:2023-11-30 13:19:04 32 4
gpt4 key购买 nike

我目前正在 Visual Studio 2015 中编写 C# Web Api。我实际上复制粘贴了很多代码。

public class APIController : ApiController
{
[HttpGet]
[Route("api/drones")]
public HttpResponseMessage getDrones()
{
var drones = db.drones.Select(d => new DroneDTO
{
iddrones = d.iddrones,
//more stuff
});
HttpResponseMessage res = Request.CreateResponse(HttpStatusCode.OK, drones);
return res;
}

[HttpGet]
[Route("api/drones/{id}")]
public HttpResponseMessage getDrones(int id)
{
var drone = db.drones.Select(d => new DroneDTO
{
iddrones = d.iddrones,
//more stuff
}).Where(drones => drones.iddrones == id);
HttpResponseMessage res = Request.CreateResponse(HttpStatusCode.OK, drone);
return res;
}
}

我应该如何重构它?起初我想将 var 移动到类成员,但这似乎是不允许的。

最佳答案

我会制作一个适用于 IQueryable<T> 的 DTO 工厂方法然后这两个函数将只负责创建正确的查询。

当您将这些函数设为异步时,这将使您在未来处于更好的位置。

    public class DroneDTO
{
public int Id { get; set; }
public static IEnumerable<DroneDTO> CreateFromQuery(IQueryable<Drone> query)
{
return query.Select(r=> new DroneDTO
{
Id = r.Id
});
}
}


public class APIController : ApiController
{
[HttpGet]
[Route("api/drones")]
public HttpResponseMessage getDrones()
{
var drones = DroneDTO.CreateFromQuery(db.drones);

HttpResponseMessage res = Request.CreateResponse(HttpStatusCode.OK, drones);
return res;
}

[HttpGet]
[Route("api/drones/{id}")]
public HttpResponseMessage getDrones(int id)
{
var drone = DroneDTO.CreateFromQuery(db.drones.Where(d => d.iddrone == id));

HttpResponseMessage res = Request.CreateResponse(HttpStatusCode.OK, drone);
return res;
}
}

关于C# WebApi重构选择Linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32476754/

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