Return anonymous type results?

后端 未结 16 1418
梦毁少年i
梦毁少年i 2020-11-22 03:01

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         


        
16条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 04:01

    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.

提交回复
热议问题