Wednesday, April 7, 2010

Including Average Ratings in LINQ-to-SharePoint

One of the joys of working with pre-released software is the lack of resources whenever you run up against an issue. My issue came up when I had to include the Average Rating field for a document library in SharePoint 2010 in a LINQ to SharePoint query. SPMetal by default will not include that column when it generates the entity classes. After digging through Reflector, scouring the internet unsuccessfully (as any search for "rating" would obviously be), and flirting with insanity (you know, trying the same thing over and over again and yet expecting different results) I was able to get it. Who would have guessed that "Invalid" is a valid field type? So, if anybody has the same issue, here are two routes to get it to work:

SPMetal Configuration XML

The easy option is to actually do what is recommended and override the SPMetal defaults with a parameters.xml file. Simply add the following line to your XML file and it will include the column.

<Column Name="Rating (0-5)" Member="AverageRating" />

 

Extending the Partial Class

The other route would be to create another partial class for the object you need and add the following property. I recommend doing this in another partial class in case you need to regenerate the classes.

private object _averageRating;

/// <summary>

/// Average value of all the ratings that have been submitted

/// </summary>

[Microsoft.SharePoint.Linq.ColumnAttribute(Name="Rating (0-5)", Storage="_averageRating", FieldType="Invalid")]

public object AverageRating {

    get {

        return this._averageRating;

    }

    set {

        if ((value != this._averageRating)) {

            this.OnPropertyChanging("AverageRating", this._averageRating);

            this._averageRating = value;

            this.OnPropertyChanged("AverageRating");

        }

    }

}