Linq随机读取数据浅析

来源:互联网 发布:hadoop php开发 编辑:程序博客网 时间:2024/05/18 02:16

学习Linq时,经常会遇到Linq随机读取数据问题,这里将介绍Linq随机读取数据问题的解决方法

Linq随机读取数据

在系统自由生成的o/p mapping代码中添加这个方法,如果是用户自己编写的(或是工具生成的)o/p mapping代码也是同理。这里我就说下我自己的。系统生成的LINQ To Sql类会产生三个文件.Northwind.cs、Northwind.dbml.layout、Northwind.designer.cs

我们要做的就是在Northwind.designer.cs中去添加我们需要的方法NEWID(),这个方法的功能当然就是和数据库当中的NEWID()是功能一致的。

具体的方法法代码如下:

  1. [System.Data.Linq.Mapping.DatabaseAttribute(Name="Northwind")]  
  2. public partial class NorthwindDataContext : System.Data.Linq.DataContext  
  3. {  
  4.  
  5. private static System.Data.Linq.Mapping.
    MappingSource mappingSource = new AttributeMappingSource();  
  6. //在自动生成的mapping code中添加  
  7. [Function(Name = "NEWID", IsComposable = true)]  
  8. public Guid NEWID()  
  9. {  
  10. return ((Guid)(this.ExecuteMethodCall(this,
    ((MethodInfo)(MethodInfo.GetCurrentMethod()))).ReturnValue));  
  11. }  
  12. //后面的生成代码略..
 

重新生成,编写好这个,我们的访问实现就变的很容易了,其使用方式和传统访问原理一致。

  1. db = new NorthwindDataContext();  
  2. var result = (from c in db.Customers orderby db.NEWID() select c).Take(10);  
  3.  
  4. foreach (var item in result)  
  5. Console.WriteLine(item.CompanyName);  
  6.  
  7. Console.ReadLine();
 

以上介绍Linq随机读取数据。