如何首先在 entity framework 代码中 select 一个变量中的多个列?

How to select multiple columns in one variable in entity framework code first?

我在 sql(歌手、专辑)中有两个表,现在我的查询如下

IQuerable<AlbumVM> = (
    from c in context.Singers 
    join d in context.Albums on c.SingerID equals d.SingerID
    select new AlbumVM()
    { 
        SingerName = c.SignerName,
        AlbumsName = d.AlbumName
    } );

现在假设一个歌手有 50 列,这个查询 returns 我有 50 行,那么我需要遍历它。

我觉得我在这里遗漏了一些东西。 有什么方法可以让我只获得一条记录吗

SingerName , Albums[]

我正在使用 Entity framework 代码优先。

你可以试试这样加入群组

How to: Perform Grouped Joins (C# Programming Guide)

Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
            Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
            Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
            Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };

            Pet barley = new Pet { Name = "Barley", Owner = terry };
            Pet boots = new Pet { Name = "Boots", Owner = terry };
            Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
            Pet bluemoon = new Pet { Name = "Blue Moon", Owner = terry };
            Pet daisy = new Pet { Name = "Daisy", Owner = magnus };

     // Create two lists.
            List<Person> people = new List<Person> { magnus, terry, charlotte, arlene };
            List<Pet> pets = new List<Pet> { barley, boots, whiskers, bluemoon, daisy };


var query = from person in people
             join pet in pets on person equals pet.Owner into gj
             select new { OwnerName = person.FirstName, Pets = gj };

在示例中比较所有者,即人对象,但在您的情况下 属性 将进行比较

var query = from c in context.Singers 
            join d in context.Albums on c.SingerID equals d.SingerID into gj
             select new { SingerName = c.SingerName, Albums = gj };

如果您首先使用代码,您应该在 AlbumsSingers

上有一个外键
public class Album
{
   public int Id {get;set;}
   public virtual Singer Singer {get;set;}
}

public class Singer
{
   public int Id {get;set;}
   public virtual ICollection<Album> Albums {get;set;}
}

那么你只需要

var singers = (
    from s in context.Singers.Include("Albums")
    select s);

这会给你一个歌手集合,每个歌手都会有一个专辑集合

foreach(var s in singers)
{
   foreach(var a in s.Albums)
   { 
      //
   }
}

要从 MasterAlbums 中获取相册名称,您只需展开 Include。它应该是这样的

var singers = (
    from s in context.Singers.Include("Albums.MasterAlbum")
    select s);

那么每张专辑都会有 属性 个 MasterAlbum.Name

@model IEnumerable<MvcApplication1.Models.Singer>
<dl>
    @foreach (var s in Model)
    {
        <dt>s.Name</dt> // Singer Name
        <dd>
            <ul>
                @foreach (var a in s.Albums)
                {
                    <li>a.MasterAlbum.Name</li> // Album Name
                }
            </ul>
        </dd>
    }
</dl>