首页 > 解决方案 > 如何通过 ID 获取记录

问题描述

如何通过 ID 获取记录?我有以下代码在 asp.net 核心控制器中创建主详细信息页面,我能够使用以下代码获得所有产品并且工作完美

界面

public interface IProductService { Task<IList<ProductDTO>> GetProduct(); }

控制器动作

public IActionResult Index()
{
    return View();
}

[HttpGet]
public async Task<IActionResult> GetProducts()
{
    var products = await ProductsService.GetProducts();
    return Json(products);
}

但是如何通过 Id 获取单个记录来创建详细信息页面。我试过这个但不起作用

public IActionResult Detail()
{
    return View();
}

[HttpGet]
public async Task<IActionResult> GetProductsDetail(int id)
{
    var products = await ProductsService.GetProducts.find(id);
    return Json(products);
}

获取产品代码

public class GetProducts_Action : BaseEFAction<GetProducts_Action_Request, GetProducts_Action_Response>
    {
        public IFileProvider FileProvider { get; }

        public GetProducts_Action(ILogger<GetProducts_Action> logger, DBContext context, ITransactionManager scope, IFileProvider fileProvider) : base(logger, context, scope)
        {
            FileProvider = fileProvider;
        }

        protected override Task<GetProducts_Action_Response> PerformActionAsync(GetProducts_Action_Request request)
        {
            IList<ProductDTO> product;

            using (var file = System.IO.File.OpenText(FileProvider.GetFileInfo("Product.json").PhysicalPath))
            {
                var serializer = new JsonSerializer();
                product = (IList<ProductDTO>)serializer.Deserialize(file, typeof(IList<ProductDTO>));
            }

            return Task.FromResult(new GetProducts_Action_Response { Products = product });
        }
    }

    public class GetProducts_Action_Request : BaseActionRequest
    {

    }

    public class GetProducts_Action_Response : BaseActionResponse
    {
        public IList<ProductDTO> Products { get; set; }
    }
}

标签: c#asp.net-core

解决方案


鉴于您的数据源实际上是一个文件而不是数据库,无论如何您每次都将反序列化该文件。那是你的性能瓶颈。因此,如果您愿意,您可以使用现有的 GetProducts() 服务方法,然后在控制器中进行过滤(使用 LINQ)。这不是一种超级干净的方式(代码方面),但性能基本相同。

[HttpGet]
public async Task<IActionResult> GetProductsDetail(int id)
{
    // Get all the products and then filter by id
    // change "a.Id" to the actual DTO Id property name if different
    var product = (await ProductsService.GetProducts()).FirstOrDefault(a => a.Id == id);
    if (product != null) {
       // If we found something, return that single ProductDTO
       return Json(product);
    } else {
       // Not Found or whatever you want
       return NotFound();
    }
}

FirstOrDefault() 将返回具有所需 ID 的第一个对象(假设 ProductDTO 属性称为 Id)。如果它没有找到任何东西,它将返回 null,所以你可能想要返回 404 Not Found 或类似的东西。


推荐阅读