简体   繁体   English

使用EF Core从多对多获取某些列

[英]Get certain columns from many to many using EF Core

In a many to many relation i would like only to get certain columns from the Referencia table like Id and Name to populate a selectlist. 在多对多关系中,我只想从Referencia表中获取某些列(例如Id和Name)以填充选择列表。 Problem is that I haven't done this before using Linq and I don't understand what is the best way to do this process. 问题是在使用Linq之前我还没有做过此事,而且我不知道执行此过程的最佳方法是什么。

Here are my models. 这是我的模特。

public class Celula
{
    public int Id { get; set; }
    public string Nome { get; set; }
    public string UAP { get; set; }
    public ICollection<MatrizCelulaReferencia> Matrizes { get; set; }
}

public class Referencia
{
    public int Id { get; set; }
    public string Nome { get; set; }
    public bool IsActivo { get; set; }
    public ICollection<MatrizCelulaReferencia> Matrizes { get; set; }
}

public class MatrizCelulaReferencia
{
    public int Id { get; set; }

    public int CelulaId { get; set; }
    public Celula Celula { get; set; }


    public int ReferenciaId { get; set; }
    public Referencia Referencia { get; set; }

    public int ObjectivoHora { get; set; }
    public int UAPId { get; set; }
    public UAP UAP { get; set; }

    public string Tipo { get; set; }
}

Here is my current query 这是我当前的查询

   var query = await _context.Referencias
                .Include(r => r.Matrizes)
                .ThenInclude(r => r.Celula)
                .Where(r => r.Matrizes.Any(c => c.CelulaId == Operador.Celula))
                .Select(x => new Referencia
                {
                    Id = // Referencia Id
                    Nome = // Referencia Name
                })
                .ToListAsync();

Right now it's kinda of a mess because I have no idea how can I select certain columns from Referencia table in this query. 现在这有点混乱,因为我不知道如何从该查询的Referencia表中选择某些列。 I only need the Id and Name 我只需要ID和名字

The x param you're passing to the lambda is a Referencia instance, so you'd just do: 您传递给lambda的x参数是Referencia实例,因此您只需执行以下操作:

.Select(x => new Referencia
{
    Id = x.Id
    Nome = x.Nome
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM