1

I have a few problems but I'm going to start with the first and smallest. I have two models with a many-many relationship, Category and Project. In each model I have an ICollection of the other model. I initialize the collection as a new HashSet() for the Project constructor and vice-versa for the Category. I've read online that this will create a new table in your database with the PK of each model as the PK in the new table. I custom named them and whatnot through Fluent API but you get the idea.

This worked out great. So I make my Controllers and create and use scaffolding to create the CRUD views. I create a few categories.. Great. Now when I get to creating a a new Project, what I want is it to show me a list of the Categories I previously created, and to require at least one be selected before pushing through the Project. The view shows no categories to select at all and allows it to go through as null. I know how to make a property required but I don't know how to make a collection property required and grab all of the categories from the database to present in the Project create view for selecting....

2
  • have you done an include on your navigation property? Commented Feb 1, 2012 at 23:44
  • No I haven't. Where would I put this? Commented Feb 1, 2012 at 23:46

2 Answers 2

2

Try :

Context.Project.Include(p=>p.Category)

inside your query code,

you will need

using System.Data.Entity;

to get the include method

Sign up to request clarification or add additional context in comments.

1 Comment

No problem, the reason you need this is because out of the box EF doesnt support lazy loading, so it actually only loads FK references when you explicitly tell it to
0

For enabling lazy load, you will also need to mark your properties as "virtual"; otherwise, you will always have to eager load them using the .Include() method.

Comments

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.