I', approaching to EF6. I have understood that, if I want a single record, I can use the First()
method (usable also like a "get", I think).
But what if I want a collection of records from my table? I mean, if the result of query can have a cardinality from 0 to N... what have I to do?
Silly Example:
Name table: SomeTable
ID NAME SOMEATTR
1 A YELLOW
2 B RED
3 C YELLOW
4 D YELLOW
5 E BLUE
...
How can I get all the records where someAttr is "yellow"?
using linq & C#
private readonly myEntities db = new myEntities()
public list<SomeTable> MyRecords()
{
return res = db.SomeTables.where(o => o.SOMEATTR == "YELLOW").ToList()
}
Once you have your Linq query...
var query = (from ... in ... where ... select ...);
Or, for your specific example:
var query = (from r in dbContext.MyTable where (r.someAttr == "YELLOW") select r);
You can either just iterate over it using foreach
which will cause it to be executed once and then yield the results ...
foreach (var r in query)
{
}
... or call ToList()
(http://msdn.microsoft.com/en-us/library/vstudio/bb342261(v=vs.100).aspx) if you want to acquire a list that can, later, be passed around, manipulated or examined many times. (This list is essentially disconnected from the server after it is returned.)
var list = query.ToList()
... or use it to construct a collection like a HashSet<T>
(http://msdn.microsoft.com/en-us/library/bb301504(v=vs.110).aspx)
var set = new HashSet<T>(query)
Any of these will cause it to be executed on the server, only once, and process the results.
After all, the query itself is IEnumerable
. It is also IQueryable
so you could manipulate it further and then enumerate the results, like...
var sortedList = query.OrderBy(...).ToList()