Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does Linq-to-SQL run the query?

Tags:

c#

linq-to-sql

Can you tell me where Linq2SQL executes the query against my sql server? I'm hoping it happens after I map to my domain object called Car.

public class Car
{
    public Guid CarId { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
    public int HorsePower { get; set; }
}

public class CarRepository
{
    private readonly MyDataContext _dc;

    private readonly Func<DbCar, Car> _mappedCar =
        c => new Car
                 {
                     CarId = c.CarId,
                     HorsePower = c.HorsePower,
                     Make = c.Make,
                     Model = c.Model,
                 };

    public CarRepository(MyDataContext dc)
    {
        _dc = dc;
    }

    public Car GetCar(Guid carId)
    {
        var car = _dc.GetTable<DbCar>()
            .Select(_mappedCar)
            .Single(c => c.CarId == carId);                

        return car;
    }        
}
like image 651
Byron Sommardahl Avatar asked Aug 10 '26 12:08

Byron Sommardahl


1 Answers

That's correct. Execution of the SQL query is deferred until Single() is called. You can confirm this by breaking the query down like this and adding a breakpoint:

var carQuery = _dc.GetTable<DbCar>().Select(_mappedCar)  // <= breakpoint
var car = carQuery.Single(c => c.CarId == carId);

If you run a profiler against your database, you should see where the query is executed as you step through the code.

More info here: LINQ and Deferred Execution

like image 114
Chris Fulstow Avatar answered Aug 13 '26 03:08

Chris Fulstow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!