- Published on
Extension Methods with OpenAccess
- Authors
- Name
- Steve McNiven
- @stevemcniven
This is a really cool thing to do in order to extend your OpenAccess Domain Model Context. You can create an entire set of helper functions which instantly have access to the calling Context object.
First step is to define the Extension class
public static class ProductExtensions{
public static Product Get(this IQueryable<Product> products, int productId){
return products.FirstOrDefault(x => x.ID.Equals(productId));
}
}
What this does is Extend the Products Collection property of your context. So now everytime you need to get a product based on it’s ID, you just have to do the following instead of the longer Linq predicate.
var product = this.Context.Get(10); //Where the productID is 10, and this.Context is your model context object.
However we can also use this to extend the Context as well
public static List<Product> GetTunaProducts(this StoreModel context) {
return context.Products.Where(x => x.Name.Contains("Tuna")).ToList();
}
So to use this you could just call
var products = this.Context.GetTunaProducts();
Another great tip is being able to get a reference to your context object from INSIDE the extension method without needing to pass it in as a variable.
public static IList<CommonLocation> GetTaggedLocations(this IQueryable<CommonLocation> locations, List<string> tags) {
//Get the context based from the persistant collection
var context = AuthDB.Model.Context.GetContext(locations.First()) as AuthDB.Model.Context;
//You dont need to do a .First() if the object being passed isn't a
//collection, so for example if it was just "this CommonLocation"
//I can send my query though a different table than CommonLocation now!
var p = (from l in context.CommonLocationLocationTags
where tags.Contains(l.CommonLocationTag.Tagname)
select l.CommonLocation);
return p.ToList();
}