0

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?

JED
  • 1,538
  • 2
  • 19
  • 47
  • 1
    Don't use entity models if you're going to be modifying them. Use a DTO that is completely distinct from the entities. – DavidG Jan 15 '19 at 16:04
  • Your requirement is not clear! Would tell me please which filtered data are you expecting from `GetCabins()` method and why are you using `foreach` in `GetCabins()` – TanvirArjel Jan 15 '19 at 16:06
  • @DavidG I do have DTOs. So, what you're saying is that I should alter the data after it's converted to the DTO? – JED Jan 15 '19 at 16:06
  • @DavidG your suggestion worked swimmingly. – JED Jan 15 '19 at 16:31

2 Answers2

0

Use .toList() on the cabins object which will create a copy for use in the loop:

 foreach (var cabin in cabins.toList()) {

See ToList()-- Does it Create a New List? for more information.

BHigzz
  • 45
  • 1
  • 5
0

After assigning

var cabins = _context.Cabins.ToList();

you assign new occupants in _context data object. And later, if you write

_context.SaveChanges();

it saves DB. Try this one

public List<Cabin> GetCabins() 
{
    // retrieve list of all cabins
    var cabins = _context.Cabins.ToList();
    List<Cabins> cabintemp= new List<Cabins>();

    // only show current occupants of the cabins
    cabintemp.occupants=cabins.occupants.Where(o => 
                o.StartDate <= DateTime.UtcNow && 
                o.EndDate >= DateTime.UtcNow)

    }

    return cabintemp;
}

Use cabintemp.

Mhsn
  • 495
  • 4
  • 12