1

Is there a faster/better way to do this?
I have here a simple one to many relationship.

public class Professor
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual IEnumerable<Subject> Subjects { get; set; }
}

public class Subject
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ProfessorId { get; set; }
    public virtual Professor Professor { get; set; }
}

Implementation ////////////////////////////////////

    public ActionResult Index()
    {
        TestDBContext db = new TestDBContext();

        var profs = db.Professors.ToList();
        var subjs = db.Subjects.ToList();

        var vm = new ProfStudVM()
        {
            Professors = profs,
            Subjects = subjs
        };

        return View(vm);
    }

View - Loading subject for each professor

<div>
@foreach (var prof in Model.Professors)
{
    <p>@prof.Name</p>
    foreach (var subj in Model.Subjects)
    {
        if (subj.ProfessorId == prof.Id)
        { 
            <span>@subj.Name , </span>
        }
    }
    <hr />
}
</div>
Middleman
  • 111
  • 1
  • 12
  • 1
    If you have set up you models and relationships correctly, then `Professor` will contain its collection of `Subject` and all you would need is `foreach (var subj in prof.Subjects) { @subj.Name , }` –  May 10 '16 at 04:17

2 Answers2

1

Suppose that you are using Entity Framework, and there is a one-many relationship from Professor to Subject.

Instead of loading all Subject, we only need to load some subjects which have their professor, using eager loading. Your code will be:

public ActionResult Index()
{
    TestDBContext db = new TestDBContext();

    // Remember to add using System.Data.Entity
    var profs = db.Professors.Include(x => x.Subjects).ToList();

    return View(profs);
}

Then, in the view, you just do like this:

<div>
    @foreach (var prof in Model)
    {
        <p>@prof.Name</p>
        foreach (var subj in prof.Subjects)
        {
            <span>@subj.Name , </span>
        }
        <hr />
    }
</div>

The code is not tested, but I believe it works well.

Triet Doan
  • 11,455
  • 8
  • 36
  • 69
-1

Ad-hoc query does not compile and haven't Execution Plan so when you use Indexed View you gain the performance better than linq query that join tables on the fly without index and execution plan. but this usefull when you have huge data and or load. in other hand you can use Automapper to flatten complex objects like this https://github.com/AutoMapper/AutoMapper/wiki/Flattening to simplify mapping ViewModel to Model And Vise Versa. I have used Automapper in some of my projects and I've been able to simplify my projects. you must trade off based on your needs.