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:
using (var ctx = new HRDataContext(webUrl))
{
var emps = ctx.EmployeeCollection.First(e => e.Id == id);
}
is equivalent to this:
using (var ctx = new HRDataContext(webUrl))
{
var emps = ctx.EmployeeCollection.Where(e => e.Id == id).First();
}
That just is not working in SharePoint. This query is equivalent to the following:
using (var ctx = new HRDataContext(webUrl))
{
var emps = ctx.EmployeeCollection.ToList().Where(e => e.Id == id).First();
}
If the list of about 10-20 records, you may not notice performance degradation.
Conclusion
Do not use .First(
2. Analog of IN operator in SQL
There is no any implementation of it in Linq-To-SharePoint and expressions like this:
using (var ctx = new HRDataContext(_webUrl))
{
var vipIds = new [] { 1, 5, 9, 23, 57, 198, 345);
var emps = ctx.EmployeeCollection.Where(e => vipIds.Contains(e.Id));
}
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:
using (var ctx = new HRDataContext(_webUrl))
{
string.Empty
var emps = ctx.EmployeeCollection.ScopeToFolder(string.Empty);
}
Conclusion
Plan the ability to create folders in lists or document libraries
4. Saving an item in the list/library folder
To create item into specifi folder of SharePoint list it's necessary only to set Path property of object. Like this:
var query = ctx.DocumentCardCollection
.ScopeToFolder(string.Empty, true)
.Where(d => d.Date >= DateTime.Today.AddDays(-5));
var card = query.First();
card.Path = "/WebUrl/ListUrl/Folder1/SubFolder2";
Hope it's helpful