Craig Schwarze
Craig Schwarze

Reputation: 11615

ASP.NET MVC - updating foreign keys

I am just starting to investigate ASP.NET MVC, and I am using the latest beta (ie. 4). I'm after the correct approach to what is a fairly CRUD scenario. My main table (Task) looks something like this -

TaskID (int) EmployeeID (int) ProjectID (int) DeptID (int) Comment (varchar) Date (datetime) Hours (float)

TaskID is the primary key. The other three IDs are all foreign keys into reference tables.

Following various tutorials, I created an object model (.edmx) using Entity Framework. I then autogenerated the controller using "Add... Controller" and selecting the "Controller with read/write..." template.

All worked well. However, obviously I want the three foreign key columns to display lookup values from the reference tables, rather than the ID. I'm really not sure what the "best practice" method for achieving this is. A few options occur to me -

  1. Create a view in SQL Server
  2. Create a view in EF (not sure how this is done)
  3. Look up the reference values on the fly using LINQ in the controllers

Perhaps there are other ways. I would like to hear from experienced MVC progs regarding "best practice" in this scenario.

Upvotes: 0

Views: 1046

Answers (1)

Pravin Pawar
Pravin Pawar

Reputation: 2569

would prefer to have TaskViewModel class which will have properties something like this

public class TaskViewModel
{
    public Task Task { get; set; }
    public Dictionary<int, string> ProjectList { get; set; }
    //rest of the Lookup Properties like DeptList, EmpList
}
public class Task
{
    public int TaskId { get; set; }
    public int projectId { get; set; }
    //Rest of the properties
}

And would use

@model TaskViewModel
@Html.DropDownListFor(m => m.Task.projectId, new SelectList(Model.ProjectList, "key", "value", Model.Task.projectId))%>  

Upvotes: 2

Related Questions