How to make a list from multiple rows from inner join in Entity Framework Core? c# entity-framework entity-framework-core linq


I have a view model called Pictures like

Public class PicturesViewModel
    public string Name;
    Public List<String> FileNames;

and I have 2 tables in a SQL Server database, Names and FileNames, where the idname in FileNames is a foreign key to id in Names.

This screenshot shows the 2 tables

I use Entity Framework Core in an ASP.NET Core MVC project. I have to use the database first method and I want to fill PicturesViewModel class in my controller and send it to a view.

The problem is that I can't find a way to create a PicturesViewModel object from DbContext with linq and Entity Framework. The only way I can consider is to do it by C# (for or foreach) and do it with 2 steps:

  • first filling Name
  • then filling FileNames with a for/foreach loop

Is there another way in Linq or Entity Framework to create a list from an inner join in dbContext ?

7/7/2018 8:22:34 AM

Accepted Answer


Public class Filenames
    public decimal idName { get; set; }
    public string fileNames { get; set; }
    public Names Names { get; set; }

Public class Names 
    public decimal id { get; set; }
    public string Name { get; set; }


With Join basic (Bad) =>

                   nam =>,
                   fil => fil.idName,
                   (nam, fil) => new { filename = fil, names = nam });

With Navigation properties (Common in DB First) =>

Context.Names.Include(ent => ent.Filenames);
7/7/2018 8:27:44 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow