Linq to Sharepoint. Part 1

Part 1. First()/FirstOrDefault(), T-SQL IN, Path
Part 2. Count(), Take(), Skip(), JOIN, ObjectTracking
Part 3. Anonymous access, Resolve list by URL
Part 4. Dynamic LINQ, Convert SPListItem to data context object
Part 5. Choice and MultiChoice fields

There is a Linq to SharePoint data provider in SharePoint 2010. Not without features. Here are some of those that I've "found".

1. First() / FirstOrDefault()

Who worked with Linq-to-SQL or Entity Framework knows that the query form:

  1. using (var ctx = new HRDataContext(webUrl))
  2. {
  3.   var emps = ctx.EmployeeCollection.First(e => e.Id == id);
  4. }
is equivalent to this:
  1. using (var ctx = new HRDataContext(webUrl))
  2. {
  3.   var emps = ctx.EmployeeCollection.Where(e => e.Id == id).First();
  4. }
That just is not working in SharePoint. This query is equivalent to the following:
  1. using (var ctx = new HRDataContext(webUrl))
  2. {
  3.   var emps = ctx.EmployeeCollection.ToList().Where(e => e.Id == id).First();
  4. }
If the list of about 10-20 records, you may not notice performance degradation.
Conclusion: do not use .First(<filter>) method without pre-filtering.

2. Analog of IN operator in SQL

There is no any implementation of it in Linq-To-SharePoint and expressions like this:

  1. using (var ctx = new HRDataContext(_webUrl))
  2. {
  3.   var vipIds = new [] { 1, 5, 9, 23, 57, 198, 345);
  4.   var emps = ctx.EmployeeCollection.Where(e => vipIds.Contains(e.Id));
  5. }
doesn't work. In this case it throw up an exception. It necessary to upload data from a list into the memory (by call .ToList() method, for exmaple) and then use .Contains().
Conclusion: use .Contains() method only for objects in the memory

3. Retrieve data from a folder

By default Linq-to-SharePoint retrieves items from root folder of a list (document library). For retrieving data from subfolders or specific folder it's necessary to use .ScopeToFolder(rootFolder,recursiveFlag) method which parameters are these:
rootFolder - path to target folder (string.Empty for the root folder);
recursiveFlag - true to include items in subfolders; false to exclude them.
Example:

  1. using (var ctx = new HRDataContext(_webUrl))
  2. {
  3.   string.Empty
  4.   var emps = ctx.EmployeeCollection.ScopeToFolder(string.Empty);
  5. }
Conclusion: plan the ability to create folders in lists or document libraries

4. Сохранение элемента в папке списка/библиотеки

To create item into specifi folder of SharePoint list it's necessary only to set Path property of object. Like this:

  1. var query = ctx.DocumentCardCollection
  2.         .ScopeToFolder(string.Empty, true)
  3.         .Where(d => d.Date >= DateTime.Today.AddDays(-5));
  4. var card = query.First();
  5. card.Path = "/WebUrl/ListUrl/Folder1/SubFolder2";

Hope it's helpful


Share

Comments