开发者

Select many rows from a data store using Linq to Entities

We need to accept a collection of key values from user input. Then a query must be performed on a L2E data store which shall select all rows whose keys are included in the collection. The best I've got so far is:

var lines = dataStore.Entities.ToList(); /* To List to force a query */
var selectedLines = lines.Where(line=> inputValues.Contains(line.key)).Distinct();
开发者_运维技巧

However, this seems seems wasteful since we're pulling the entire data store in order to select (probably) just a small number of rows. Would it be less wasteful to execute a separate query matching each key value (the column is indexed) or is there a better way with Linq syntax that I've missed?


EF4 has support for contains so you can just use it directly.

var selectedLines = dataStore.Entities
                             .Where(line=> inputValues.Contains(line.key))
                             .Distinct();

For possible workarounds in earlier versions see this SO question.


You should have the contains within your first query.
This will then only return the values that the user specifiec.
I would also recomend you look at LinqPad very nice tool and it shows you what queries are being create by Linq to Entities.

var lines = (from p in dataStore.Entities
            where inputValues.Contains(p.key)
            select p).ToList();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜