Return anonymous type results?

Using the simple example below, what is the best way to return results from multiple tables using Linq to SQL?

Say I have two tables:

Dogs:   Name, Age, BreedId
Breeds: BreedId, BreedName

I want to return all dogs with their BreedName. I should get all dogs using something like this with no problems:

public IQueryable<Dog> GetDogs()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select d;
    return result;
}

But if I want dogs with breeds and try this I have problems:

public IQueryable<Dog> GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new
                        {
                            Name = d.Name,
                            BreedName = b.BreedName
                        };
    return result;
}

Now I realize that the compiler won’t let me return a set of anonymous types since it’s expecting Dogs, but is there a way to return this without having to create a custom type? Or do I have to create my own class for DogsWithBreedNames and specify that type in the select? Or is there another easier way?

16 Answers
16

Leave a Comment