开发者

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.

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.


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>() } );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜