When seeding an entity and its children using SQL into a SQL server database, the children do not appear when retrieved with EF Core. However, when inserting the entity and its children using EF Core, all related entities are retrieved. How can I ensure that the children of a seeded entity are retrieved when using EF Core?

Suppose you have an Order entity that has a collection of OrderItems as its children. You seed an order and its order items into the SQL Server database using SQL scripts. When you retrieve the order using Entity Framework Core, the order items are not included in the result. However, if you insert the order and its order items using Entity Framework Core, all related entities are retrieved as expected.

Here's an example of the SQL script used to seed the order and its order items:

INSERT INTO Orders (Id, OrderDate) VALUES (1, '2022-01-01');  
INSERT INTO OrderItems (Id, OrderId, ProductName, Quantity) VALUES (1, 1, 'Product A', 2);  
INSERT INTO OrderItems (Id, OrderId, ProductName, Quantity) VALUES (2, 1, 'Product B', 1);  

And here's an example of how you retrieve the order using Entity Framework Core:

var order = _dbContext.Orders.FirstOrDefault(o => o.Id == 1);  

In this example, order will only contain the Order entity and not its related OrderItems.

I should add that I have set up LazyLoading using Lazy Loading with proxies: https://learn.microsoft.com/en-us/ef/core/querying/related-data/lazy

    options.UseSqlServer(builder.Configuration.GetConnectionString(""))
          .UseLazyLoadingProxies();
0

There are 0 best solutions below