2

我有两个具有一对多关系的实体,我正在尝试在子项中选择主实体过滤属性。

例如:

public class Pedido
{
    public int Id { get; set; }
    public string Descricao { get; set; }
    public virtual ICollection<PedidoItem> Itens { get; set; }
}


public class PedidoItem
{
    public int Id { get; set; }
    public int PedidoId { get; set; }
    public Pedido Pedido { get; set; }
    public string Descricao { get; set; }
    public int Status { get; set; }
}


public class DataInit : DropCreateDatabaseAlways<Data>
{
    protected override void Seed(Data context)
    {
        context.Pedidos.Add(new Pedido {
            Descricao = "PEDIDO UM",
            Itens = new List<PedidoItem> { 
                new PedidoItem { 
                    Descricao = "ITEM UM", 
                    Status = 0 },
                new PedidoItem{
                    Descricao = "ITEM DOIS",
                    Status = 0 },
                new PedidoItem{
                    Descricao = "ITEM TRES",
                    Status = 0 },
                new PedidoItem{
                    Descricao = "ITEM QUATRO",
                    Status = 1 }
            }
        });

        context.SaveChanges();

        base.Seed(context);
    }

    public DataInit()
    {

    }
}
public class Data : DbContext
{
    public DbSet<Pedido> Pedidos { get; set; }
    public Data()
    {
        Database.SetInitializer(new DataInit());
    }
}

class Program
{
    static void Main(string[] args)
    {
        Data dt = new Data();
        var pedidos = from ped in dt.Pedidos
                      where ped.Itens.Any(item => item.Status == 1)
                      select ped;

        var lista = pedidos.ToList();
    }
}

我在数据库中只有一个 Pedido 实体和一个状态 = 1 的项目,我只想返回集合中状态 = 1 的项目,我该怎么办?

我想返回仅包含一项已过滤的 Pedido 实体(item.Status == 1)

4

1 回答 1

1

准确地得到你想要的东西有点困难,但我认为是这样的:Pedidos只有一个Iten(项目?)并且其中一个项目有Status == 1

那将是:

from ped in dt.Pedidos
where ped.Itens.Count() == 1
from it in ped.Itens.Where(i => i.Status == 1)
select ped // or new { ped.Property1, ..., it.Description }

在流利的语法中,这转换为 a SelectMany,但这是综合(或查询)语法更容易遵循的情况之一。(虽然 Were 是流利的语法)。

于 2012-07-21T17:41:12.083 回答