tags:

views:

24

answers:

1

Consider the following expression:

from p in db.People
    select new Person {
        Name = p.Name, Age = p.Age, Gender = p.Gender.ToEnum<Gender>()
};

It works to the point of calling extension method static T ToEnum<T>(this string value); as expected.
I understand why there is do not know how to translate string to enum error.
Question is: how do I work around this without introducing another class?
I mean that I could define class PersonWithGenderAsText and then translate that into Person class, but I feel there got to be an easier way.
Specifically, I don't mind calling .ToList() on the result of the expression above, but I cant figure out the rest.

+3  A: 

Just use an anonymous inner type to fetch just the bits you want from the database, use AsEnumerable to switch to "in process" mode, and then you can do the transformation into a Person object:

var query = db.People
              .Select(p => new { p.Name, p.Age, p.Gender } )
              .AsEnumerable()
              .Select(p => new Person { Name = p.Name,
                                        Age = p.Age,
                                        Gender = p.Gender.ToEnum<Gender>() } );

If there's no more data in db.People you could simplify this further:

var query = db.People
              .AsEnumerable()
              .Select(p => new Person { Name = p.Name,
                                        Age = p.Age,
                                        Gender = p.Gender.ToEnum<Gender>() } );
Jon Skeet