0

I have a question.

My question actually extends from this one:

Shortly - what I want to get: 3 models, and 1 super model for this specific view. This super model fills(properly) IENumerable, IENumerable, IENumerable, to use them in View part. (as far as I understand it, at least...)

In this other topic Dan Revell proposed verry nice and elegant solution, but this solution does not fetch data from DB itself...

Question: What must be done to get data in this model from DB, not from "new" instance constructors?

While using this approach tried to fetch data from DBContext. And got some problems in it ) I can't understand when (or how) to create my DBContext... Or how to access one that is created by application...

Tried to create it forcefully in Controller, like

using (var Db = new thetaskermvc.Models.TaskerDBContext())
    {
        var themodel = new thetaskermvc.Models.TotalView();
        //Jobbers
        themodel.Jobberz = new Dictionary<int, thetaskermvc.Models.Jobbers>();
        var jobbers = from Jobbers in Db.Jobbers.OrderBy(g => g.jobb_name) select Jobbers;
        foreach (Models.Jobbers ad in jobbers)
        {
            themodel.Jobberz.Add(ad.jobb_id,
                     new Models.Jobbers(ad.jobb_id, ad.jobb_name, ad.jobb_from, ad.jobb_carma, ad.jobb_status, ad.jobb_balance, ad.jobb_time));
        }
        if (themodel.Jobberz.Count == 0)
        {
            themodel.Jobberz.Add(-1, new Models.Jobbers(0, "NOTHING FOUND",DateTime.Now,0,"",0,0));
        }

   }

But as created that way Context stops it's existence (?) after passing data away from controller - I can't use it any other way but to get all data inside this controller, and fill data in model by direct add into collections in it (while use of IENumerable would fetch data on-demand, as far as I get it).

So.. If it ain't hard please enlighten me about - is it Ok to use such approach, or there is some other "common" way? Becaus beside it's clumsiness - this approach works...

PS I'm quite new to Asp, yet...

Community
  • 1
  • 1
Der Zinger
  • 506
  • 7
  • 13

2 Answers2

3

I have one view model per view with data from multiple tables (if required). On my view I have data that needs to be loaded from 2 different database tables. In my grant application controller I have the following:

private readonly IBankService bankService;
private readonly IAccountTypeService accountTypeService;

public GrantApplicationController(IBankService bankService, IAccountTypeService accountTypeService)
{
     // Check incoming parameters for null values

     this.bankService = bankService;
     this.accountTypeService = accountTypeService;
}

In my Create action method I populate my banks and account types (to be used in drop downs) like this (different tables):

public ActionResult Create()
{
     GrantApplicationCreateViewModel viewModel = new GrantApplicationCreateViewModel
     {
          Banks = bankService.FindAll(),
          AccountTypes = accountTypeService.FindAll()
     }

     // Do what ever else you need to get done

     return View(viewModel);
}

My partial view model would like this:

public class GrantApplicationCreateViewModel
{
     public int BankId { get; set; }
     public IEnumerable<Bank> Banks { get; set; }
     public int AccountTypeId { get; set; }
     public IEnumerable<AccountType> AccountTypes { get; set; }

     // Other properties
}

In my repository class I would use the database context like this (I use Entity Framework code first):

public class BankRepository : IBankRepository
{
     HefContext db = new HefContext

     public IEnumerable<Bank> FindAll()
     {
          return db.Banks.OrderBy(x => x.Name);
     }
}

In my database context class:

public class HefContext : DbContext
{
     public DbSet<Bank> Banks { get; set; }
     public DbSet<AccountType> AccountTypes { get; set; }
}

Doing it this way you can have one view model that has data from multiple sources. I hope this answers your question? If you need more explanation please let me know :)

Brendan Vogt
  • 25,678
  • 37
  • 146
  • 234
  • Perfectly answers my question! I can see exactly what had to be done and how :) Thanks a lot. – Der Zinger Mar 21 '12 at 14:14
  • 1
    Great answer. I would like to add that if you're using Data Entities that have been imported, you can skip the repository all together, by using your Linq queries directly into the creation of the model by the controller, [and here is an example of what I'm talking about.](http://pastebin.com/vhgiNzyy) – Spencer Cole Jul 27 '12 at 20:04
1

You may want to have a look at this post, it explains (with a sample project) how an ideal MVC application architecture should be.

In your code sample above, your shouldn't have any references to DbContexts in a controller. Controller's job is to control the flow of requests not to connect to the DB and perform Model population.

amythn04
  • 388
  • 2
  • 11
  • DataAccess in a controller action is fine for small projects. The problem is that your Persisted Model is NOT a View Model. The model in MVC is a View Model, a model that represents the View. It has NO correlation to the Persisted Model or Domain Model or anything. – Phill Mar 20 '12 at 08:51
  • Yes, that is exactly what I need ) a "Proper" structure. Thx. – Der Zinger Mar 21 '12 at 14:12
  • Sry, but the upper post is more an "Answer" to my question... But this link that you gave is more than useful... So sry, but only my gratitute is what I can give :) And I can't even voteup yet... – Der Zinger Mar 22 '12 at 11:36