4

I'm trying to upgrade a large application which uses Entity Framework 4 to use Entity Framework 5. I've discovered a function like this:

public FooModel(FooEntity foo)
{
    _foo = foo;
    _foo.bars.Load(System.Data.Objects.MergeOption.OverwriteChanges);
}

Where foo and bar are generated entities, with bar having a foreign key to foo.

It seems EF5 no longer has the .Load(MergeOption) function, and I've never seen it before. Does anyone know what it does, and what its equivalent is?

https://stackoverflow.com/a/13178313/784908 suggests that Load is part of DbContext - but my entity container inherits from DbContext, and still isn't available


My best guess is that it is used for Eager loading of the foreign keys (which I need to do, the context is created and disposed of many times in a request, and there is no guarentee it will exist/attached when FooModel is used)

Entity Framework - eager loading of related entities shows I should be using .Include(), but that function doesn't seem to be available on an actual entity (I think the term is 'materialized query'?)

Thanks for reading

Community
  • 1
  • 1
berkeleybross
  • 1,314
  • 2
  • 13
  • 27

1 Answers1

1

.Load() loads an IQueryable query from database into the memory - in fact, Local property of the relevant entity of your DbContext.

You can use this method with any IQueryable collection, not just the DbContext. Examples are as the following:

var q = db.Products.Include("Category").ToList();
q.Load(); // -> you can't!

// ------------

db.Products.Include("Category").Load(); // It's OK!

// This will NOT query the database, just looks in-memory data.
var p = db.Products.Local.Single(id); 

// ------------

var q = db.Products.Include("Category").ToList();
q.AsQueryable().Load(); // -> It's OK!

// This also will NOT query the database, just looks in-memory data.
var p = db.Products.Local.Single(id); 

The load function is mainly used for 2 reasons:

1) Retrieving some parts of data from Db to memory and work with them:

db.Products.Include("Category").Where(p => p.CatId == 10).Load();

2) To be able to use Linq-to-Objects methods which L2E doesn't supports(like .ToString(), etc.) - as the Local property of DbContext entities are ObservableCollection<T> which implements IEnumerable, just as L2O objects:

db.Products.Include("Category").Where(p => p.CatId == 10).Load();
string subName = db.Products.Local.Find(id).SubString(0, 4);
Amin Saqi
  • 18,549
  • 7
  • 50
  • 70