1

A very newbie question about MVC and Entity Framework (using data driven development).

I built an EF model off an existing database. I used the EF wizard/tool in Visual Studio, pointed it to my database, and it created all the entity classes and relationships.

Assume it is simple database that has two tables and following columns:

Table 1
uid (pk)
name
description

Table 2
id (pk)
uid (fk to Table 1)
class

I want a view/page that will display Table 2 but instead of uid, display name from Table 1.

Right now, my controller just passes the Table2 entity model to the view but obviously, it doesnt contain the cross reference value for uid.

Do I need to create a separate view model for this? If so, what do i put in it? Or, can I extend the EF generated entity model to somehow contain the associated values from Table1?

2
  • Are you at all familiar with linq? Commented May 10, 2014 at 1:28
  • It would be helpful to see your controller Commented May 10, 2014 at 1:34

2 Answers 2

2

You should find yourself relying heavily on view models - its rare that you need all of a given entity's properties (table's cells) - nothing more or less. Viewmodels provide you with that functionality - the ability to provide a given view with exactly the properties it needs.

Whether you're using a viewmodel or not, because you have a foreign key between the tables, you won't need to do anything special to get data from both. As I said in my comment though, I'll need to see your controller to ensure that the model passed to the view contains all the data you'll need.

In your view, you'll reference your model at the top of the page, like this...

@model yourprojectnamespace.yourentitynametable1forinstance

Then, you'll be able to reference an item from the model like this,

@Model.table1item

You can also reference properties from the other table like this...

@Model.table1.table2.table2item
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this. I'm also reviewing the MVC4 Pro Framework book by APress.
1

You should use viewmodel to pass data to view.

You can move only required properties.
What is ViewModel in MVC?
WebApi Controller returned value in Entity Framework 5 and MVC 4 project
you can add additional/custom validation rules to view model

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.