Reputation: 13012
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;
}
}
Upvotes: 3
Views: 160
Reputation: 41902
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
Upvotes: 7