0

How can I convert next SQL query to Entity Framework

SELECT 
  customers."CustomerId",
  customers."CustomerName",
  "Orders"."OrderId",
  "Orders"."Description",
  "Orders"."CustomerId",
  "OrderDetails"."OrderDetailId",
  "OrderDetails"."Article",
  "OrderDetails"."OrderId"
FROM
  "Orders"
  RIGHT OUTER JOIN customers ON ("Orders"."CustomerId" = customers."CustomerId")
  LEFT OUTER JOIN "OrderDetails" ON ("Orders"."OrderId" = "OrderDetails"."OrderId")

What I have tried:

public List<customers> GetAll() 
{ 
    var custord= _dbContext.customers .Include(x => x.Order) .Include(x => x.OrderDetails) .ToList(); return custord;
    
}

The problem: If I have Order without OrderDetail information I can not get all records.

ER Diagram looks like ER Diagram

6
  • EF deals with entities and objects, not tables and joins. If you have Order, Customer and OrderDetail classes with navigation properties ie Order.OrderDetails, Customer.Orders, Order.Customer, then EF will generate the JOINs when you execute eg context.Customers.Include(c=>c.Orders).ThenInclude(o=>o.OrderDetails).ToList(). As long as you follow naming conventions all you have to do is define the DbSet<T> properties Commented Mar 20, 2024 at 15:16
  • ORMs like EF or NHibernate try to give the impression of working with in-memory objects instead of tables and rows. If you have to use JOINs, it means something is missing Commented Mar 20, 2024 at 15:18
  • What have you tried, and what result did you get versus what result did you expect? There are a ton of tutorials out there on how to query using EF. Please show your research and attempts. Commented Mar 20, 2024 at 15:20
  • public List<customers> GetAll() { var custord= _dbContext.customers .Include(x => x.Order) .Include(x => x.OrderDetails) .ToList(); return custord; } If I have Order without OrderDetail information I can not get all records Commented Mar 20, 2024 at 16:06
  • See here for how to do a left join Commented Mar 20, 2024 at 16:44

1 Answer 1

0

This is solution, thanks all:

var item = (
from Order in _dbContext.Orders
join Customer in _dbContext.Customers on Order.CustomerId equals Customer.CustomerId
join OrderDetail in _dbContext.OrderDetails on Order.OrderId equals OrderDetail.OrderId
select new
{
    CustomerId = Customer.CustomerId,
    CustomerName = Customer.CustomerName,
    OrderId = Order.OrderId,
    Description = Order.Description,
    OrderDetailId = OrderDetail.OrderDetailId,
    Article = OrderDetail.Article,

}).ToList();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.