Question

I am going through some trouble with EF. In this model I would like to get an IEnumerable of all Products whose names match some string, but also the Products inside an Order whose name ALSO matches the same string, all of this without Product duplicates in the resulting IEnumerable.

That is, a query that searches the same string and matches it against BOTH the Product's name and the Order's name and returns the matched Products.

Thanks

      public class Order
        {
            public Order()
            {             
                OrderDetailList= new  List<OrderDetail>();
            }

            public int Id { get; set; }
            public String orderName{ get; set; }            
            public ICollection<OrderDetail> OrderDetailList{ get; set; }    
        }

 public class OrderDetail 
    {

        public int Id { get; set; }        

        [ForeignKey("Product_Id")]
        public Turno Product { get; set; }
        public int Product_Id { get; set; }

        public int numberOfItems{ get; set; }

        [ForeignKey("Order_Id")]      
        public Order Order { get; set; }
        public int Order_Id { get; set; }
   }



 public class Product 
    {
        public Product()
        {         
            OrderDetail= new List<OrderDetail>();
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public string codId { get; set; }
        public ICollection<OrderDetail> OrderDetailList{ get; set; }
}



public class Context : DbContext
    {
        public Context()
            : base("Context") { }            
        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderDetail> OrderDetails { get; set; }
        public DbSet<Product> Products { get; set; }
    }
Was it helpful?

Solution

This is how I understand the description of what you'd like to query:

var products = context.Products
    .Where(p =>
        p.Name == "searchString" ||
        p.OrderDetailList.Any(od => od.Order.orderName == "searchString"))
    .ToList();

OTHER TIPS

Use Include while querying on the product like so

context.Product.Distinct().Include(o =>
OrderDetailList.Product.Where(p=>p.Name.Contains("string")).ToList();

I have not tested the example so you might need to adjust it a bit. But you get the idea I gues.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top