Linq to sharepoint的引入的确给我们操作Sharepoint带来了便利,首先就体现在对Sharepoint 的查询优势上。它基本可以照搬Linq to SQL的查询语法,这就大大保护了你的学习成本,当然,它们之间有某些差异(如:在List间的Left Outer Join等处)
  在实践本处的知识点前,首先需要搭建我们的测试环境。这里我们仍旧引入Northwind数据库的数据表:Customers,Orders,Order Details和Products。我们要用到它们是因为我们要利用它里面的数据快速创建出我们Sharepoint网站的List内容(我们要在Sharepoint网站上创建出4个CustomerLists: ACustomer,AOrders,AOrderDetails和AProducts)。
  如何搭建此环境,请参照

  Sharepoint学习笔记---SPList--使用Linq to Sharepoint间接查询External List(1.通过BCS创建External List)

  Sharepoint学习笔记---SPList--使用Linq to Sharepoint间接查询External List(2.复制External List内容)

  Sharepoint学习笔记---SPList--使用Linq to Sharepoint间接查询External List(3.使用Linq to Sharepoint查询List内容)
  当然你也可以想其它办法创建相应的Sharepoint List环境(eg:通过Excel表导入),总之,此处不再赘述如何搭建学习环境。
  我们创建好的List如下

Sharepoint学习笔记---Linq to Sharepoint--查询语法

 

  下面分别列举查询语法:
  首先,在程序顶部我们定义了四个Entity变量并给它们赋值,即从Sharepoint网站的相应List中取出List的内容赋值给对应的Entity Classes 

        EntityList<ACustomerItem> MyCustomers;
        EntityList<AOrdersItem> MyOrders;
        EntityList<AOrderDetailsItem> MyOrderDetails;
        EntityList<AProductsItem> MyProducts;
       var dc = new NorthWindEntityDataContext(SPContext.Current.Web.Url);
        MyCustomers = dc.GetList<ACustomerItem>("ACustomer");
        MyOrders = dc.GetList<AOrdersItem>("AOrders");
        MyOrderDetails = dc.GetList<AOrderDetailsItem>("AOrderDetails");
        MyProducts = dc.GetList<AProductsItem>("AProducts");

 接下来就是使用上面的 MyCustomers,MyOrders,MyOrderDetails,MyProducts进行各种查询。 

 1.ACustomer中所有的CustomerID(Distinct查询)  

View Code
var distinctCustomers = (from dcustom in MyCustomers select dcustom.BCSFindCustomerID).Distinct();

 2.查询所有有定单的Customer 

View Code
 var query = from c in MyCustomers
             where (from o in MyOrders
                                   select o.BCSFindCustomerID).Contains(c.BCSFindCustomerID)
                            select c;

 3.查询所有没有定单的Customer 

View Code
var query = from c in MyCustomers
            where !(from o in MyOrders
                                select o.BCSFindCustomerID).Contains(c.BCSFindCustomerID)
                        select new
                        {
                            CopanyName = c.BCSFindCompanyName,
                            ContanctName = c.BCSFindContactName,
                            Address = new
                            {
                                Country = c.BCSFindCountry,
                                City = c.BCSFindCity,
                                PostalCode = c.BCSFindPostalCode
                            }

                        };

 4.判断Customer的Country是否属于欧洲国家


                        };

相关文章: