Skip to content

Writing custom manager classes

misonou edited this page Sep 14, 2016 · 3 revisions

Custom model managers can be build from the abstract SPModelManagerBase class.

The main different to the derived SPModelManager class is that all querying methods are protected members. This allow you to expose custom query methods.

Modify query before execution

There are also 3 virtual methods that allow overriding default querying behaviors namely

  • OnExecutingListQuery
  • OnExecutingSiteQuery
  • OnExecutingKeywordSearch

You can add additional filter expressions to the query or set different behaviors on the query before execution.

Default manager type

There are occasions that the manager are implicitly created:

  • SPModel.CreateManager() creates instance of the default manager type for the specified model type;
  • SPModel.TryCreate() creates instance of model class from the list item which also creates instance of manager which the model belongs to;
  • The parent manager of instance handling item events.

By default the manager type for model class T is SPModelManager<T>. To change that to your defined manager class, annotate your model class by SPModelManagerDefaultTypeAttribute:

[SPModelManagerDefaultType(typeof(MyItemManager))]
public class MyItem : SPModel {
}

public class MyItemManager : SPModelManagerBase<MyItem> {
}

ISPModelManager manager = SPModel.CreateManager(typeof(MyItem), SPContext.Current.Web);
Assert.IsInstanceOfType(manager, typeof(MyItemManager)); // OK