How to manipulate PetaPoco result set after fetch is complete?

148 views Asked by At

I have created some classes to enable fetching data from multiple tables:

[PetaPoco.TableName("Employees")]
class Employee {
    public int Id { get; set; }
    public FirstName { get; set; }
    ...
}

[PetaPoco.TableName("Tickets")]
class Ticket {
    public int Id { get; set; }
    public string Details { get; set; }
    ...
    [PetaPoco.Ignore]
    public Employee employee { get; set; }
}

Now in one controller, I am fetching data from the database and returning the result in the response body:

[HttpGet]
public IEnumerable<Ticket> Get() {
    var db = new Database("DefaultConnectionString");
    var result = db.Query<Ticket, Employee>("select * from tickets t left join employees e on t.employee_id = e.id");

    return result;

}

All of this works fine. But the problem is when the Details column contains too many characters. I want to limit the number of characters returned in the response to, say: 30. I don't want the limitation to happen at the database level, rather right before the result is returned in the response.

Here is what I imagine how to do it, but the compiler won't allow this:

return result.Select(x => { x.Details = x.Details.Substring(0, 30); });   // doesn't work
return result.Select( (t, e) => { t.Details = t.Details.Substring(0, 30); });   // doesn't work
return result.Select(x => { x.Details = x.Details.Substring(0, 30); }, y=> {});   // doesn't work

How can modify the Details property of all items before returning in the response?

1

There are 1 answers

0
Plebsori On

The .Selects you've shown aren't returning the correct instance. This should work

return result.Select(x => 
{ 
    x.Details = x.Details.Substring(0, 30);
    return x;
});