Return anonymous type results?

后端 未结 16 1138
梦毁少年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

    Well, if you're returning Dogs, you'd do:

    public IQueryable<Dog> GetDogsWithBreedNames()
    {
        var db = new DogDataContext(ConnectString);
        return from d in db.Dogs
               join b in db.Breeds on d.BreedId equals b.BreedId
               select d;
    }
    

    If you want the Breed eager-loaded and not lazy-loaded, just use the appropriate DataLoadOptions construct.

    0 讨论(0)
  • 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<Dog>, 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<Dog> GetDogs()
    {
        using (var db = new DogDataContext(ConnectString))
        {
            db.LoadOptions.LoadWith<Dog>(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);        
    }
    
    0 讨论(0)
  • 2020-11-22 03:38

    Just select dogs, then use dog.Breed.BreedName, this should work fine.

    If you have a lot of dogs, use DataLoadOptions.LoadWith to reduce the number of db calls.

    0 讨论(0)
  • 2020-11-22 03:39

    You can return anonymous types, but it really isn't pretty.

    In this case I think it would be far better to create the appropriate type. If it's only going to be used from within the type containing the method, make it a nested type.

    Personally I'd like C# to get "named anonymous types" - i.e. the same behaviour as anonymous types, but with names and property declarations, but that's it.

    EDIT: Others are suggesting returning dogs, and then accessing the breed name via a property path etc. That's a perfectly reasonable approach, but IME it leads to situations where you've done a query in a particular way because of the data you want to use - and that meta-information is lost when you just return IEnumerable<Dog> - the query may be expecting you to use (say) Breed rather than Ownerdue to some load options etc, but if you forget that and start using other properties, your app may work but not as efficiently as you'd originally envisaged. Of course, I could be talking rubbish, or over-optimising, etc...

    0 讨论(0)
  • 2020-11-22 03:41

    In C# 7 you can now use tuples!... which eliminates the need to create a class just to return the result.

    Here is a sample code:

    public List<(string Name, string BreedName)> 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();
    
        return result.Select(r => (r.Name, r.BreedName)).ToList();
    }
    

    You might need to install System.ValueTuple nuget package though.

    0 讨论(0)
  • 2020-11-22 03:42

    You can not return anonymous types directly, but you can loop them through your generic method. So do most of LINQ extension methods. There is no magic in there, while it looks like it they would return anonymous types. If parameter is anonymous result can also be anonymous.

    var result = Repeat(new { Name = "Foo Bar", Age = 100 }, 10);
    
    private static IEnumerable<TResult> Repeat<TResult>(TResult element, int count)
    {
        for(int i=0; i<count; i++)
        {
            yield return element;
        }
    }
    

    Below an example based on code from original question:

    var result = GetDogsWithBreedNames((Name, BreedName) => new {Name, BreedName });
    
    
    public static IQueryable<TResult> GetDogsWithBreedNames<TResult>(Func<object, object, TResult> creator)
    {
        var db = new DogDataContext(ConnectString);
        var result = from d in db.Dogs
                        join b in db.Breeds on d.BreedId equals b.BreedId
                        select creator(d.Name, b.BreedName);
        return result;
    }
    
    0 讨论(0)
提交回复
热议问题