0

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?

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

4 Comments

I'm assuming Customers means Employees in my case? Where am I meant to be doing this?
@link664 - Yes. You're correct. I fixed the typo. And you can do the first when first loading the entities from the database and the second anywhere in code as long as the original context is still valid.
The second one worked, although i think there may be a typo here as well with the extra exclamation mark before the Load call? The entity framework actually creates an BusinessReference property so the code ended up being employee.BusinessReference.IsLoaded, etc.
@link664 - Sorry for the additional typos. That's what I get for answering from an iPad on a bus. Both are fixed along with a little extra detail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.