唐山网站建设

设为主页 加入收藏 繁體中文

Cast的妙用:泛用LINQ 語句

核心提示:泛用LINQ语句的概念很简单,在1些情况下,我们会有需求使用同1段程式码来对不同资料表做查询,这在ADO.NET中很轻易到达,见下例:

甚么是泛用LINQ 语句

泛用LINQ语句的概念很简单,在1些情况下,我们会有需求使用同1段程式码来对不同资料表做查询,这在ADO.NET中很轻易到达,见下例:

以下为援用的内容:
static void PrintCustomerID(SqlDataReader reader)
{
    Console.WriteLine(reader.GetString(reader.GetOrdinal("CustomerID")));
}

此函式接受1个Reader物件,然后顷印CustomerID栏位值,这不受限于SqlDataReader所选取的Schema或是资料表,只要Schema中有CustomerID栏位即可。

不过,这样的手法在LINQ这类Typed-Query(具型别查询语句)模式下,并没有很直觉的写法,由于你不能写下下面的句子。

以下为援用的内容:
static void Test2(int index)
{
      var query;
      DataClasses1DataContext context = new DataClasses1DataContext();
      context.Log = Console.Out; //for log only,you can remove it.
      if (index == 1)
          query = context.Customers;
      else
          query = context.Orders;
 
      var result = from s1 in query where s1.CustomerID.Contains("V")
                   select s1;
      foreach (var item in result)
      {
         Console.WriteLine(item.CustomerID);
      }
}

编译器会抱怨,var的变数必须在宣布时指定。那要如何在LINQ To SQL或是LINQ To Entites到达一样的效果呢?这有几个方法可以做到。

1、使用ExecuteQuery,并使用另1个Typed物件来接收回传集。

2、使用实体种别(Entity Class)继续。

3、使用Cast与partial class。

1与2对熟习LINQ To SQL的读者应当不难,所以我就不再赘述了,第3个手法是较少见的,我们可以应用partial class机制,让Entity Classes实作特定介面,然后以Cast函式来到达目的。

以下为援用的内容:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.SqlClient;
 
namespace ConsoleApplication39
{
    class Program
    {
        static void Main(string[] args)
        {
            Test(1);
            Console.WriteLine("------");
            Test(0);
            Console.ReadLine();
        }
 
        static void Test(int index)
        {
            IQueryable query = null;
            DataClasses1DataContext context = new DataClasses1DataContext();
            context.Log = Console.Out; //for log only,you can remove it.
            if(index == 1)
                query = context.Customers.Cast();
            else
                query = context.Orders.Cast();
 
            var result = from s1 in query where s1.CustomerID.Contains("V") select s1;
            foreach (var item in result)
            {
                Console.WriteLine(item.CustomerID);
            }
        }
    }
 
    public inte***ce IGenericBaseClass
    {
        string CustomerID { get; set; }
    }
 
    partial class Customers : IGenericBaseClass
    {
    }
 
    partial class Orders : IGenericBaseClass
    {
    }
}

仔细揣摩上面的代码,我相信你会找到1个不1样的LINQ利用手法。

唐山网站建设www.fw8.net


TAG:内容,手法,语句,物件,程式
评论加载中...
内容:
评论者: 验证码: