Todd Davis
Todd Davis

Reputation: 6033

MVC/EF Basics - how to return values from mixed tables/objects in MVC/EF?

I am fairly new to MS MVC - so far I have created the basic template base project (Home and About pages) and used EF to hook up to our existing DB. The application is a basic survey application.

In the database, each survey record has a CreatedBy column with a GUID. That GUID maps back to our Logins database table, it is the UserID of the member.

OK, so using the scaffolding built into VS, I created controller for each main object we work with, including the Login and Survey objects. The scaffolding created an Index() in the SurveyController, it looks like this:

    public ViewResult Index()
    {
        return View(db.Surveys.ToList());
    }

When I run the app, everything lists very nice, but in the CreatedBy column is a big ugly GUID. This isn't very helpful, I really want to show the name of the actual member associated with that GUID.

What is the best way to accomplish this? I thought about altering the Survey object, adding a LoginName field, and populating that, but that "breaks" the code in that, if I want to update the scaffolding later, I will lose any changes I make here.

I'm sure this is a common issue. I'm wondering if there is a best practice to combine cross-table/cross-object data when returning a View?

Upvotes: 0

Views: 161

Answers (1)

Mark Stafford - MSFT
Mark Stafford - MSFT

Reputation: 4336

My personal (non-MSFT-approved) advice is to consistently try to use "Code First" and to stay away from ObjectContext if at all possible. Even if you have an existing database, you can still use Code First by reverse engineering the database with the power tools (still in CTP1). More specifically, this question and many of the questions you are likely to encounter in the near future are likely to be answered in the tutorials on MSDN. We (the EF team) worked closedly with the ASP.NET MVC team to make sure these tutorials are high quality, and it sounds like exactly what you need. Make sure to look in the left nav bar for a good starting point.

Upvotes: 1

Related Questions