1

I want to create endpoint which return the data by username(string).

Finding by id is working. It list the data with the given id.

app.MapGet("/store/{id}", async (StoreDb db, int id) => await db.Stores.FindAsync(id))
   .RequireAuthorization();

But using name(string) is not working.

app.MapGet("/store/{name}", async (StoreDb db, string name) => await db.Stores.FindAsync(name))
   .RequireAuthorization();

Schema :

Store {
    id integer($int32)
    name string
}

Json :

{
  "id": 0,
  "name": "string"
}
haldo
  • 14,512
  • 5
  • 46
  • 52
jsancho
  • 55
  • 4

1 Answers1

2

It's not working because the method FindAsync tries to find your record using the id, you're only passing a different data in his parameter, what you should do is something like this

app.MapGet("/store/{name}", async (StoreDb db, string name) => await db.Stores.Where(s => s.name == name).FirstOrDefault()).RequireAuthorization();

But retrieving by name can generate some problems when there's redundant names so you should change FirstOrDefault() to ToListAsync() which is better for this case

app.MapGet("/store/{name}", async (StoreDb db, string name) => await db.Stores.Where(s => s.name == name).ToListAsync()).RequireAuthorization();
Kvble
  • 286
  • 1
  • 8