Home > other >  Entity Framework does not fetch the rows that have a relationship
Entity Framework does not fetch the rows that have a relationship

Time:02-23

I have these 2 tables in a SQL Server:

Table #1 Order:

OrderID    
Name
IsFetched

Table #2 OrderRows:

OrderRowId    
OrderID    
Name
Adress

These tables have a relationship on the OrderID column: one order can have multiple OrderRows that are connected to the Order table by the OrderID key.

However, when I query the database using Entity Framework 6, I don't get the OrderRows that belong to the Order, they are always null, why is that? Aren't the OrderRows supposed to automatically be populated?

    using (var db = new MyDbEntities())
    {
        db.Configuration.LazyLoadingEnabled = false;

        try
        {
            var list = db.Order.Where(x => x.IsFetched == null || x.IsFetched == false).ToList();
            return list;
        }
        catch (Exception ex)
        {
            return null;
        }
    }

CodePudding user response:

You have to Include the related entities by adding .Include(x => x.OrderRows)


   using (var db = new MyDbEntities())
    {
        db.Configuration.LazyLoadingEnabled = false;
        try
        {
            var list = 
                 db.Order
                  .Include(x => x.OrderRows)
                  .Where(x => x.IsFetched == null || x.IsFetched == false)
                  .ToList();
            return list;
        }
        catch (Exception ex)
        {
            return null;
        }
    }
  • Related