nam
nam

Reputation: 23868

EF-Core Eager Loading to a ViewModel

In my ASP.NET Core 1.1 with EF Core 1.1 app, I've a scenario similar to the following: Parent table PT and child table CH have 1-1 FK-relationship. We need to get a few columns from certain records from PT table, and a few columns from associated records from the CH table. Question: How can I load these records to the following ViewModel using the following LINQ query? Note: I can have it done using regular LINQ Join etc but was curious as to how we can do it using Eager Loading

ViewModel:

public class PT_CH_ViewModel
{
Public int PTCol1 {get; set;}
Public string PTCol1 {get; set;}
Public float PTCol1 {get; set;}
....
Public int CHCol1 {get; set;}
Public string CHCol2 {get; set;}
....
}

Controller: Need to load PT_CH_ViewModel here and return it as a list

....
PT pt = _context.PT
                .Include(p => p.CH)
                .Where(p => p.PTcol == selectedID);
....
return View(???);

Upvotes: 0

Views: 779

Answers (1)

jegtugado
jegtugado

Reputation: 5141

You need to have a navigation property for your CH entity. Once eager loaded, you can then access the navigation property's content.

public class PT
{
    public int Col1 { get; set; }
    ...
    public virtual CH CH { get; set; } // optional, do not put [Required] attribute
}

public CH
{
    public int Col1 { get; set; }
    ...
    [Required] // CH table needs PT table for the 1-1 relationship
    public PT PT { get; set; }
}


PT_CH_ViewModel viewModel = new PT_CH_ViewModel()
{
    PTCol1 = pt.Col1,
    PTCol2 = pt.Col2,
    PTCol3 = pt.Col3,
    CHCol1 = pt.CH.Col1,
    CHCol2 = pt.CH.Col2
};


return View(viewModel);

Since you need it as a list, you can do something like:

var pts = _context.PT
                .Include(p => p.CH)
                .Where(p => p.PTcol == selectedID)
                .Select(pt => new PT_CH_ViewModel()
                {
                    PTCol1 = pt.Col1,
                    PTCol2 = pt.Col2,
                    PTCol3 = pt.Col3,
                    CHCol1 = pt.CH.Col1,
                    CHCol2 = pt.CH.Col2
                }).ToList();

return View(pts);

View:

@model List<PT_CH_ViewModel>

Upvotes: 2

Related Questions