0

With following DDD and the repository pattern, is it possible to return the aggregate root object with its child data already included instead of using lazy loading?

e.g. I have a warehouse entity as the aggregate root and it has a child object called location.

On the repository I have a method below to query the location Id but passes back the warehouse entity.

dim warehouse as Warehouse = warehouseRepository.FindByLocationId(Id as int32).
dim locationName as string = warehouse.location.where(function(x) x.Id = 1).firstordefault.name

When I use warehouse.location EF uses a proxy class to fire off another DB query to retrieve the location data. In my repository method FindByLocationId can I query the location DB table and pass back the warehouse entity with the location data included?

user1180223
  • 111
  • 8

2 Answers2

1

In general to stop lazy loading and proxies you can set the following properties on the Configuration property of your DbContext class. I tend to do this when overriding the OnModelCreating() method, so all my 'Setup' stuff is together.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;


        base.OnModelCreating(modelBuilder);
    }

If you want to eagerly load a property you can use the Include() method:

var wareHouse = (from w in ctx.WareHouses.Include("location")
                select w).FirstOrDefault();
David Masters
  • 8,069
  • 2
  • 44
  • 75
  • With the include statement it pulls back all the child records for warehouse, I only want to show 1 child record which i am querying for. I tried the following code but it still shows all the location records. Dim wareHouse = (From w In DataContextFactory.GetWMSDBContext.StockWarehouse Join sl In DataContextFactory.GetWMSDBContext.StockLocation On sl.WarehouseID Equals w.Id Where sl.Id = locationId Select w).FirstOrDefault() – user1180223 Jun 07 '12 at 10:09
0

I presume you just want to use the include option in your query. http://msdn.microsoft.com/en-us/library/bb896272.aspx

So you'd have something like this:

var data = (from w in context.Warehouse
            .Include("Location")
            select w).FirstOrDefault();
Chris Moutray
  • 18,029
  • 7
  • 45
  • 66