Hi @Ronald Rex , Welcome to Microsoft Q&A,
You can add some logic inside the method to check if the child record exists. If there are no child records, the related loops and method calls are not executed.
public static List<Customer> LoadCustomers()
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var customers = cnn.Query<Customer>("select * from Customer", new DynamicParameters());
List<Customer> result = customers.ToList();
foreach (var customer in result)
{
List<Order> orders = LoadCustomerOrders(customer.Id);
// Check if there are orders before assigning them to customer
if (orders.Any())
{
customer.Orders = orders;
foreach (var order in orders)
{
List<OrderDetails> orderDetails = LoadOrderDetails(order.Id);
// Check if there are order details before assigning them to order
if (orderDetails.Any())
{
order.OrderDetails = orderDetails;
}
}
}
}
return result;
}
}
public static List<Order> LoadCustomerOrders(int customerId)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var orders = cnn.Query<Order>("select * from Orders where Orders.CustomerID=" + customerId, new DynamicParameters());
List<Order> result = orders.ToList();
return result;
}
}
public static List<OrderDetails> LoadOrderDetails(int id)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var orders = cnn.Query<OrderDetails>("select * from OrderDetails where OrderDetails.OrderId=" + id, new DynamicParameters());
List<OrderDetails> result = orders.ToList();
return result;
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.