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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
John Lee
  • 1,357
  • 1
  • 13
  • 26

2 Answers2

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
tintyethan
  • 1,772
  • 3
  • 20
  • 44
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

Community
  • 1
  • 1
aamir sajjad
  • 3,019
  • 1
  • 27
  • 26