I have a database with the following tables:
create table Categories (
Id int primary key,
Name nvarchar(256) not null)
create table Products (
Id int primary key,
Name nvarchar(256) not null,
CategoryId int not null,
foreign key (CategoryId) references Categories (Id))
Using DataLoadOptions
, I can write this:
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Category>(c => c.Products);
and get all of the category and product information in one query.
However, db.Categories.First()
, db.Categories.FirstOrDefault()
, and db.Categories.Take(10)
will execute a query that only grabs a subset of entries from the Categories
table, and nothing else. Essentially, this:
SELECT TOP (1) Id, Name FROM Categories
-- and
SELECT TOP (10) Id, Name FROM Categories
Accessing the Products
property of a Category
instance will result in another query execution.
I've discovered a few ways to get around this.
// For First():
var category = db.Categories.Single(c => c == db.Categories.First());
// For FirstOrDefault():
var category = db.Categories.SingleOrDefault(c => c == db.Categories.First());
// For Take(10):
var categories = db.Categories.Where(c => db.Categories.Take(10).Contains(c));
All of the LINQ statements above will return all of the category and product information for a subset of Categories
entries in one query each.
Does anyone know if there is a better or more efficient way of achieving this? Thanks.