When learning about LINQ, you will often encounter the problem of Random Data Reading by LINQ. Here we will introduce the solution to the problem of Random Data Reading by LINQ.
Random Data Reading by LINQ
O/P mapping freely generated in the systemCodeAdd this method. If the O/P mapping code is compiled by the user or generated by the tool, the same is true. Here I will talk about my own. The System-generated LINQ to SQL class generates three files:. northwind. CS, northwind. dbml. layout, and. northwind. Designer. CS.
All we need to do is add the required method newid () in the northwind. Designer. cs. The function of this method is of course consistent with the newid () in the database.
The specific method code is as follows:
- [System. Data. LINQ. Mapping. databaseattribute (name = "northwind")]
- Public partial class northwinddatacontext: system. Data. LINQ. datacontext
- {
- Private Static system. Data. LINQ. mapping.
Mappingsource = new attributemappingsource ();
- // Add it to the automatically generated mapping code
- [Function (name = "newid", iscomposable = true)]
- Public guid newid ()
- {
- Return (guid) (This. executemethodcall (this,
(Methodinfo) (methodinfo. getcurrentmethod (). returnvalue ));
- }
- // The code generated later is omitted ..
Re-Generate and write this, and our access implementation will become very easy. The usage is consistent with the traditional access principle.
- DB = new northwinddatacontext ();
- VaR result = (from C in db. Customers orderby dB. newid () Select c). Take (10 );
- Foreach (VAR item in result)
- Console. writeline (item. companyName );
- Console. Readline ();
The preceding section describes how to read data randomly by using LINQ.