Query Extensions Template
The queries template is an optional alternative to the manager template. If you don't want to use the manager framework, you can use this template to generate some common queries for an entity. While its possible to use both the manger and query templates, they do duplicate some functionality. The template works by generating an extension class for Table<Entity>. This allows the queries to be off the DataContext.
SampleDataContext db = new SampleDataContext(); Task task = db.Task.GetByKey(1);
This is an example of what the extension class looks like.
/// <summary> /// The query extension class for Task. /// </summary> public static partial class TaskQueryExtension { /// <summary> /// Gets an instance by the primary key. /// </summary> public static Task GetByKey(this Table<Task> entity, int taskID) { if (entity.Context.LoadOptions == null) return Query.GetByKey.Invoke((SampleDataContext)entity.Context, taskID); else return entity.FirstOrDefault(t => t.TaskID == taskID); } /// <summary> /// Gets a query by an index. /// </summary> public static IQueryable<Task> GetByStatusID(this Table<Task> entity, int statusID) { if (entity.Context.LoadOptions == null) return Query.GetByStatusID.Invoke((SampleDataContext)entity.Context, statusID); else return entity.Where(t => t.StatusID == statusID); } #region Query /// <summary> /// A private class for lazy loading static compiled queries. /// </summary> private static partial class Query { internal static readonly Func<SampleDataContext, int, Task> GetByKey = CompiledQuery.Compile( (SampleDataContext db, int taskID) => db.Task.FirstOrDefault(t => t.TaskID == taskID)); internal static readonly Func<SampleDataContext, int, IQueryable<Task>> GetByStatusID = CompiledQuery.Compile( (SampleDataContext db, int statusID) => db.Task.Where(t => t.StatusID == statusID)); } #endregion }
Properties on the Queries.cst template:
Property |
Description |
---|---|
1.Database |
|
SourceDatabase |
The source database to keys and indexes from for generating the manager classes. |
2.Mapping |
|
DbmlFile |
The path to the dbml file used generate the query classes from. |
3.Query |
|
QueryDirectory |
The folder to save the generated query extension files. |
MethodPrefix |
The prefix of query method names. For example 'GetBy'. |
MethodKeySuffix |
The suffix of the primary key query method names. For example 'Key'. |