I am trying to return a list of objects but only include a subset of one property of that object.
Controller
[ServiceFilter(typeof(LogUserActivity))]
public class CabinsController : Controller
{
private readonly IBaseRepository _repo;
public CabinsController(IBaseRepository repo)
{
_repo = repo;
}
public IActionResult GetCabins()
{
return Ok(_repo.GetCabins());
// upon completing the action, the LogUserActivity
// filter saves changes to the database.
}
}
Repository
public List<Cabin> GetCabins()
{
// retrieve list of all cabins
var cabins = _context.Cabins.ToList();
// only show current occupants of the cabins
foreach (var cabin in cabins) {
cabin.occupants =
cabin.occupants.Where(o =>
o.StartDate <= DateTime.UtcNow &&
o.EndDate >= DateTime.UtcNow).ToList();
}
return cabins;
}
However, this is altering _context
and the database it's connected to. It's deleting all occupants
that are not current.
How can I retrieve a subset of the object's property without altering the datasource?