Find and Include with EF 6



This works, although, I'm not really interested in the first one.

Customer foundCustomer = context.Set<Customer>().Include(e => e.Orders.Select ( d => d.OrderLines)).FirstOrDefault();

This works, and I find the match I'm working for.

string custKey = "VINET";

Customer foundCustomer = context.Set<Customer>().Include(e => e.Orders.Select(d => d.OrderLines)).Where(c => c.CustomerID.Equals(custKey, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

This works, and reads the db as I want, but does not have the includes I want.

Customer foundCustomer = context.Set<Customer>().Find(custKey);

This does not work....but is what I'm actually after

Customer foundCustomer = context.Set<Customer>().Include(e => e.Orders.Select(d => d.OrderLines)).Find(custKey);

Is there any way to combine Include() with Find() ?

Here is the Context. The typical Northwind Customer/Order(s)/OrderDetails scenario.

public partial class WindyContext : DbContext
    static WindyContext()

    public WindyContext()
        : base("Name=NorthwindContext")

    public DbSet<Customer> Customers { get; set; }
    public DbSet<OrderLine> DbSetOrderLines { get; set; }
    public DbSet<Order> Orders { get; set; }
    public DbSet<Product> Products { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        modelBuilder.Configurations.Add(new CustomerMap());
        modelBuilder.Configurations.Add(new OrderLineMap());
        modelBuilder.Configurations.Add(new OrderMap());
        modelBuilder.Configurations.Add(new ProductMap());
1/17/2014 5:18:30 PM

Accepted Answer

Nope, no such luck. I don't know why the Find() method doesn't have an overload that accepts a list of eager-load paths, but it might be because it tries to be efficient by first looking at the entities that have already been loaded into the context.

You best bet is the second example, but you can clean it up a little by putting the condition directly in the FirstOrDefault() call:

Customer foundCustomer = context.Set<Customer>()
    .Include(e => e.Orders.Select(d => d.OrderLines))
    .FirstOrDefault(c => c.CustomerID.Equals(custKey, StringComparison.OrdinalIgnoreCase));

You also might be able to use == instead of Equals() if your database/column collation is already set to case-insensitive.

1/17/2014 5:13:32 PM

Popular Answer

I don't believe that you can use "Include" when using "Find". If you wish to explicitly load the other entities, then you could give the following a try:

var customer = context.Customers.Include(x => x.Orders)
                                .SingleOrDefault(x => x.CustomerID == custKey);

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow