views:

226

answers:

3

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?

A: 

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.

mcintyre321
What do you mean? "you should be able to traverse the object model to get most of the data you need" isn't that what I'm saying I want to do with: person.Address.Zip? How can I be more clear?
Becky
sorry for being abrupt - i was trying to say that you shouldn't go off creating unneeded repository implementations, instead you should model the object relationships fully - one big Data Model should allow this.
mcintyre321
A: 

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

jfar
Thanks! This will work perfectly for how I've re-arranged my entity data models.
Becky
A: 

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?

Becky