user1180223
user1180223

Reputation: 111

DDD EF Repository

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?

Upvotes: 0

Views: 343

Answers (2)

David Masters
David Masters

Reputation: 8295

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();

Upvotes: 1

Chris Moutray
Chris Moutray

Reputation: 18399

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();

Upvotes: 0

Related Questions