Becky
Becky

Reputation: 207

Eager Loading with Entity Framework and Asp .net mvc (From a rails background)

I have a few tables that reference the same table. For example:
Person has an address.
Business has an address.

When using the models I would like to do this in the controller:

person.Address.Zip
business.Address.Zip

I'm coming from a rails background where I can just declare a relationship and have all the above functionality. Force loading of the address when I get the object (person or business).

I'm new to entity framework, and I'm struggling with how to achieve that functionality. I can't include the table in both models (person and business). If I use repository pattern and add the objects to a partial for the class, then I'm using lazy loading.

Am I looking at this wrong? Any suggestions for patterns I could use?

Upvotes: 1

Views: 1928

Answers (3)

Becky
Becky

Reputation: 207

Previously, I was creating an ADO.NET Entity Data Model for each controller.

Now I've created one Data Model for all tables (it's not a monstrous db). That way I can include the tables when I query for eager loading.

If anyone has a better suggestion. Let me know. If anyone knows the correct behavior with a large database, please comment. Would you want one large edmx file to represent the database?

Upvotes: 0

John Farrell
John Farrell

Reputation: 24754

If your using Entity Framework 4.0 with Visual Studio 2010 lazy loading is automatic.

If your using Entity Framework 1.0 your life just got harder...

To eager load with EF1 you have to use the Include() method on your ObjectQuery and specify which navigation properties ( address ). For example:

ModelContainer.Persons.Where(@p => @p.Id == 39 ).Include("Address")

For "lazy" loading you have to manually load all of the FK associations manually. For example:

var myPeople = ModelContainer.Persons.Where(@p => @p.Id == 39 

if( !myPeople.Address.IsLoaded() )
     myPeople.Address.Load()

Another option is to modify how EF1 generates your model types and include lazy loading out of gates.

http://code.msdn.microsoft.com/EFLazyLoading

Upvotes: 2

mcintyre321
mcintyre321

Reputation: 13306

Ideally you should be able to traverse the object model to get most of the data you need, starting with a reference to the current user object.

Upvotes: -1

Related Questions