EF Joins and MVC Razor Views
I have several tables whose relationships are based upon unique key constraints.
A quick example is:
VersionId, VersionName
SurveyId, SurveyName, VersionId QuestionId, QuestionName, SurveyId, VersionIdEF doesn't currently support relationships based upon unique key constraints. In my index view for question what's the best way handle the join to survey to show the grid of questions with survey name with respect to a model?
Do I need an anonymous type? db.Questions.Include("Surveys") doesn't seem to do anything. I could use linq and make a 开发者_JS百科ViewModel of the joined tables (I suspect this is the way to go), but there are so many things in EF & MVC that I thought I'd check before doing anything.
Why do you have a link to Version (i.e. VersionID) in both your survey table and your question table? Couldn't you reach the version from the question through the survey?
Also, if you have the relationship between Question and Survey is many-to-one or one-to-one (each question only has one survey) then it should be db.Questions.Include("Survey")
- non-plural.
First of all, no joins (or practically any other logic) in razors views. Controller is the place to build up the ViewModel, and views are means to just present that ViewModel. As you mentioned, making ViewModel
for it is only (correct) way to go. And you can fill that viewmodel by whatever method - linq is absolutely normal way to create joined data. And if you want to go further, you should place that join logic in some kind of repository, for example QuestionRepository
, not in controller.
精彩评论