I have two entity that has an one-to-many relationship, I´m trying to select the master entity filtering properties in the child items.
For example:
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();
}
}
I have only one Pedido entity in database and one one item with status = 1, I´d like to return only this item that has status = 1 in the collection, How should I do?
I´d like to return Pedido entity with only one item that was filtered(item.Status == 1)
It is a bit hard to get what you want exactly, but I think it is this: the
Pedidosthat only have oneIten(Item?) and of which that one item hasStatus == 1.That would be:
In fluent syntax this translates to a
SelectMany, but this is one of those cases where the comprehensive (or query) syntax is much easier to follow. (Although the Were is fluent syntax).