I am new to C# and I am currently trying the CRUD operations in it. I have done the Create, Get all details, Update, and Delete. But I am unable to get only and all the details by ID.
I have a database called ‘fuel’ and in there I have added shedId. For each shed there can be multiple fuels. Now I want to get the fuel details by each shedID.
In here you can see I have 2 data for shedID:1
But when I try to filter the db by shedID, I am getting a response like this. As I am new to C# I don’t know how to get it. I searched in the google and couldn’t find a solution.
Please help me with this.
This is the code I have tried
//Get Fuel by each shed id
[HttpGet("shed/{id}")]
public JsonResult Get(int id)
{
MongoClient dbClient = new MongoClient(_configuration.GetConnectionString("FuelQueueAppConnection"));
var filter = Builders<Fuel>.Filter.Eq("shedId", id);
var dbList = dbClient.GetDatabase("FuelQueue").GetCollection<Fuel>("Fuel").Find(filter);
return new JsonResult(dbList);
}
Summary – I have a DB called fuels. In there I have many fuels. Each fuel have a shedID and a shedID can have multiple fuels. Now I need to find the fuel list of each shedID. (Like ShedID:1 => 2 fuel details)
2
Answers
I just identified that as the result need to be a list I have to add ToList() after the filtering. I am adding the solution as it might help someone in future.
Thank you all for helping the learners.
I would suggest two things, don’t try and fit the return directly to your object use the generic so if the format changes or does not align you still have a return.
Also, if Mongo is returning a list use the .ToList() method.
This should return all the records for Shed 1, from there you would have to parse the fuel data from each record.