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, A
You must use ToList()
method first to take rows from database and then select items as a class.
Try this:
public partial class Dog {
public string BreedName { get; set; }}
List 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
}).ToList()
.Select(x=>
new Dog{
Name = x.Name,
BreedName = x.BreedName,
}).ToList();
return result;}
So, the trick is first ToList()
. It is immediately makes the query and gets the data from database. Second trick is Selecting items and using object initializer to generate new objects with items loaded.
Hope this helps.