Linq To Sql : add value transformation
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.
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.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>() } );
精彩评论