Linq随机读取数据浅析2011-08-07学习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()是功能一致的。具体的方法法代码如下:[System.Data.Linq.Mapping.DatabaseAttribute(Name="Northwind")] public partial class NorthwindDataContext : System.Data.Linq.DataContext {
private static System.Data.Linq.Mapping. MappingSource mappingSource = new AttributeMappingSource(); //在自动生成的mapping code中添加 [Function(Name = "NEWID", IsComposable = true)] public Guid NEWID() { return ((Guid)(this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod()))).ReturnValue)); } //后面的生成代码略..重新生成,编写好这个,我们的访问实现就变的很容易了,其使用方式和传统访问原理一致。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);