Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return an anonymous type in linq-to-sql

I have the following bogus code, but the idea is to return a generic class

 public static var getSeaOf(string user)
        {
            var periodsSettings = from p in sea
                                  where p.add_by == new Guid(user)
                                  select new { p.id, p.name };

            return var;
        }

I have read here - How to return anonymous type from c# method that uses LINQ to SQL that the best solution for this case is to create a class for the return type.

But my question is if I have hundreds of functions like this does it mean I need to have hundreds of classes?

I hope there is a more generic solution, thanks for your help!!


Edition

I take a look at

Silverlight - LinqToEntities - How Do I Return Anonymous Types

But I cannot specified the class name in the select new, like the article does?

public static IEnumerable<retSea> getBskSeasonsOf(string user)
        {
            var periodsSettings = from p in sea
                                  where p.add_by == new Guid(user)
                                  select new retSea { p.id, p.name };

            return periodsSettings;
        }
like image 825
roncansan Avatar asked Dec 06 '10 17:12

roncansan


1 Answers

If I remember correctly, the spec says that the anonymous type generated for that object cannot escape the method it's defined in. Therefore the only method that could ever have variables of that type is the method the object is instantiated in. This gets a bit sketchy when you consider the fact that the LINQ query could get compiled into a bunch of methods, but that's magic.

The object itself, however, can escape the method. The way to make this work is to... return object. You'll have to access it using reflection (or dynamic) though, so you'll lose type safety. You might want to consider whether this is worth it or not. Most likely it's not. And most likely you don't have hundreds of different types of results either - I bet many of your queries return the same type of data. Re-use those classes.

like image 197
Matti Virkkunen Avatar answered Sep 24 '22 11:09

Matti Virkkunen