Search code examples
javascriptbreezedurandal

Should I query on the server or on the client with BreezeJS?


I'm developing a SPA web application with Durandal and BreezeJS. On my server I have a BreezeAPI which returns my metadata, returns all data in a specific table lets say cars and which allows me to post my changes (SaveChanges).

Now lets get back to where I get all the cars with the method:

[HttpGet]
    public IQueryable<tblCar>AllCars()
    {
        return _contextProvider.Context.Car;
    }

I understand how I need to work with these but here is my question: Is it possible to query a specific car on the server? Or is this only possible on the client-side where I query over my fetched data from AllCars?


Solution

  • Just to clear, by default, all queries in Breeze are executed exclusively on the server. (You can query the local query cache but I don't think that is what you asking about.) What you can control is whether the query expression to be executed was defined exclusively on the server or is composed based on a query defined on the server along with additional client side restrictions.

    If you want to define a query on the server that returns a single record you can certainly do so. It would look something like this:

    [HttpGet]
    public Car Car17()
    {
        return _contextProvider.Context.Cars.First(c => c.CarId == 17);
    }
    

    which could be queried from the client via:

    var q = EntityQuery.from("Car17");
    

    Alternatively you could use query parameters:

    [HttpGet]
    public Car CarById(carId)
    {
        return _contextProvider.Context.Cars.First(c => c.CarId == carId);
    }
    

    for which the query would look like this:

    var q = EntityQuery.from("CarById").withParameters( { carId: 17} );
    

    or you could do something like this:

    [HttpGet]
    public IQueryable<Car> AllCars()
    {
        return _contextProvider.Context.Cars;
    }
    

    for which the query would look like this:

    var q = EntityQuery.from("AllCars").where("CarId", "==", 17);
    

    The important thing to be clear about is that all 3 of these execute exactly the same query on the server and return exactly the same results.

    Hope this helps.