Return anonymous type results?

后端 未结 16 1151
梦毁少年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 03:36

    BreedId in the Dog table is obviously a foreign key to the corresponding row in the Breed table. If you've got your database set up properly, LINQ to SQL should automatically create an association between the two tables. The resulting Dog class will have a Breed property, and the Breed class should have a Dogs collection. Setting it up this way, you can still return IEnumerable, which is an object that includes the breed property. The only caveat is that you need to preload the breed object along with dog objects in the query so they can be accessed after the data context has been disposed, and (as another poster has suggested) execute a method on the collection that will cause the query to be performed immediately (ToArray in this case):

    public IEnumerable GetDogs()
    {
        using (var db = new DogDataContext(ConnectString))
        {
            db.LoadOptions.LoadWith(i => i.Breed);
            return db.Dogs.ToArray();
        }
    
    }
    

    It is then trivial to access the breed for each dog:

    foreach (var dog in GetDogs())
    {
        Console.WriteLine("Dog's Name: {0}", dog.Name);
        Console.WriteLine("Dog's Breed: {0}", dog.Breed.Name);        
    }
    

提交回复
热议问题