要通过名称搜索数据库,您可以使用Entity Framework的LINQ查询来实现。以下是一个示例解决方案:
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions options)
: base(options)
{
}
public DbSet- Items { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped();
// ...
}
[Route("api/[controller]")]
[ApiController]
public class ItemsController : ControllerBase
{
private readonly ApplicationDbContext _context;
public ItemsController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet]
public async Task GetItems(string name)
{
var items = await _context.Items.Where(i => i.Name == name).ToListAsync();
return Ok(items);
}
// ...
}
现在,您可以通过发送GET请求到/api/items?name=your_name
来搜索数据库中名称匹配的项。请确保将your_name
替换为要搜索的名称。
希望这可以帮助到您!