Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

c# - How can I extract a list of Tuple from a specific table with Entity Framework / LINQ?

I need to extract a list of couple 'ID'/'Name' from a large table in C# .NET with Entity Framework.

I try this request :

List<Tuple<int, string>> list = (from res in db.Resource 
                                 select new Tuple<int, string>(res.Resource_ID, res.Name)).ToList();

But unfortunately I've got this error :

Only parameterless constructors and initializers are supported in LINQ to Entities.

I don't undestand how can I extract this list of tuple with this framework and I feel a bit lost with this error. Can you help me to understand and resolve my problem ?

Best regards,

Alex

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it with a middle-step by selecting an anonymous type:

db.Resource.Select(x => new { x.Resource_ID, x.Name }).AsEnumerable().Select(x => Tuple.Create(x.Resource_ID, x.Name)).ToList();

Creating a tuple is not a supported operation in Linq To Entities, so you have to select an anonymous type, which would be an equivalent to:

SELECT [Resource].[Resource_ID], [Resource].[Name]

then move to LINQ to Objects by AsEnumerable and get your tuple.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...