views:

95

answers:

1

We have 3 tables in our db that each have an entity in our edmx. To illustrate my problem, imagine 3 tables:

Table: Make
Fields:
makeID
make

Table: Model
FIelds:
modelID
makeID    foreign key
model

Table: Car
carID
modelID   foreign key
car

Our Make, Model, and Car entity have all of the navigation properties in the entity model. Lazy loading is disabled. We want to be able to pull all cars that are Jeep Grand Cherokees to output to our page.

Right now we have something like this in one of our functions (C# 4.0)

IEnumerable<Make> makeList =  (((ObjectSet<Lot>)_modelRepository.GetQuery())
         .Include(mk => mk.Models.Where(md => md.model == "Grand Cherokee"))
         .Where(mk => mk.make == "Jeep").ToList());

_makeRepository.GetQuery() returns an IQueryable ... we implement the repository pattern

This query should work fine (haven't tested it, created for ths example) but how can we .Include the car table so that our function returns Make entity objects such that the Model is populated and the Cars are populated (problem getting the Cars because they do not have a direct navigation property to Make)

We're using POCO objects.

The goal is to have 1 function returning a Make entity to be able to do this:

foreach(Make myMake in makeList)
{
    Response.Write(myMake.make);

    foreach(Model myModel in myMake.Models)
    {
         Response.Write(myModel.model);

         foreach(Car mycar in myModel.Cars)
         {
              Response.Write(mycar.car);
         }
    }
}

Something like this doesn't seem possible but its what we're going for:

IEnumerable<Make> makeList =  (((ObjectSet<Lot>)_modelRepository.GetQuery())
         .Include(mk => mk.Models.Where(md => md.model == "Grand Cherokee"))
         .Include(c => mk.Models.Cars)
         .Where(mk => mk.make == "Jeep").ToList());

I've also tried creating a new entity in my edmx that contains all of this information so that I can just query that one object but I keep getting errors saying keys must be mapped... I did map them in the Mapping tab (Visual Studio 2010)... so I'm back to trying to get the query working.

+2  A: 

I am not 100% sure but I believe you are going to need to create some kind of DTO like this:

public MakeModelCarDto
{
    public IEnumerable<Make> Makes {get; set;}
    public IEnumerable<Model> Models {get; set;}
    public IEnumerable<Car> Cars {get; set;}
}

Then you are going to have to JOIN the tables like this:

_makeRepository.GetQuery()
        .Join(_modelRepository.GetQuery(), mk => mk.makeid, mo => mo.makeid, (mk, mo) => new { mk, mo })
        .Join(_carRepository.GetQuery(), @t => @t.mo.modelid, c => c.modelid, (@t, c) => new { @t, c })
        .Where(@t => @[email protected] == "Jeep" && @[email protected] == "Grand Cherokee")
        .Select(@t => new MakeModelCarDto
        {
            Makes = @[email protected],
            Model = @[email protected],
            Cars = @t.c
        }).SingleOrDefault();
Paul