When using Linq to SQL to query multiple tables, returning anonymous type results can pose challenges. Consider a scenario where you have a Dogs table (containing Name, Age and BreedId) and a Breeds table (containing BreedId and BreedName). Retrieving all dogs is easy:
<code class="language-csharp">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; }</code>
However, trying to use an anonymous type to return a dog with the corresponding BreedName results in a compilation error:
<code class="language-csharp">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; }</code>
This is because Linq to SQL expects a Dog type to be returned, but the query generates an anonymous type.
To overcome this problem, one solution is to create a custom class to represent the desired result:
<code class="language-csharp">public class DogWithBreed { public Dog Dog { get; set; } public string BreedName { get; set; } } public IQueryable<DogWithBreed> 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 DogWithBreed() { Dog = d, BreedName = b.BreedName }; return result; }</code>
This method creates a DogWithBreed class that contains properties for Dog and BreedName. The query then selects an instance of this custom class that can be used to access the required data.
The above is the detailed content of How to Return Joined Data from Linq to SQL Without Compilation Errors?. For more information, please follow other related articles on the PHP Chinese website!