dnatoli
dnatoli

Reputation: 7012

Foreign Key problem using ADO .NET Entity Data

I am developing an ASP.NET MVC2 app with a MSSQL db using VS2008 and SQL Express 2008 R2. I have a table called Business and another table called Employee. Employee has a BusinessID foreign key as all employees must belong to a business.

I'm using the ADO .NET Entity Data Model to generate my model. From reading another post, it seems the version I have of the entity framework won't bring over foreign keys but instead create a navigation property.

I manually inserted some data into the database, creating a business with an id of 1, and an employee with a business_id of 1. Now when i try to load my index page which is a list of employees, it gives me a null reference exception because the Business object associated to the Employee object is null.

Isn't the entity model meant to fill this property for me? If not, how am I meant to create the relationship in the front end between objects if I don't have the business id coming through from the db due to the foreign key not being brought over?

Upvotes: 0

Views: 663

Answers (1)

Justin Niessner
Justin Niessner

Reputation: 245429

You have to explicitly load Navigation Properties:

entityContext.Businesses.Include("Employees");

Or if you've already loaded the Entity, you can use (for a Navigation Collection):

if(!business.Employees.IsLoaded)
    business.Employees.Load();

Or if there's a single instance:

if(!employee.BusinessReference.IsLoaded)
    employee.BusinessReference.Load();

Upvotes: 1

Related Questions