When using Linq to SQL to process multiple tables, returning anonymous types may encounter challenges. Please consider the following example:
Original method:
This method successfully retrieve all dog information. However, if we try to retrieve dogs and its variety names:
<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>
We will encounter errors because the compiler expects to return the DOG type, not anonymous type.
<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>
A solution is to create a custom class, such as Dogwithbreed:
Then you can modify the code as follows:
<code class="language-csharp">public class DogWithBreed { public Dog Dog { get; set; } public string BreedName { get; set; } }</code>
The above is the detailed content of How to Return Anonymous Types from LINQ to SQL Queries?. For more information, please follow other related articles on the PHP Chinese website!