mercredi 4 mars 2015

How to organize predefined queries with Entity Framework?


I have some queries that I use all the time (like get rows only of some specific type, or count something etc.). I'd like to organize them somehow (better then I currently do).


Currently I have them all in a static class called Queries which I don't really like because it's like a I-don't-know-how-to-name-this-class.


Is there a preferred way for organizing predefined queries in Entity Framework by extending some types etc.?




As requested here is an example showing how I use it:


All of my queries:



public static class Queries
{
public static IEnumerable<Light> GetEnabledLights()
{
using(var context = new MyEntities())
{
return context.Lights.Where(l => l.Enabled);
}
}
}


Code using some query:



public static class LightsLoader
{
public static void LoadLights()
{
var enabledLights = Queries.GetEnabledLights().ToList();
if (enabledLights.Count == 0)
{
throw new InvalidOperationException("There are no enabled lights.");
}
// ... more code
}
}


Faking the query and testing the business logic:



[TestClass]
public class LightsLoaderTests
{
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void TestNoEnableLights()
{
using(ShimContext.Create())
{
ShimQueries.GetEnabledLights = () => Enumerable.Empty<Light>();
LightsLoader.LoadLights();
}
}
}




But back to the question: I just thought Entity Framework might offer a better way for organizing queries then putting them all in a God-Class ;-)





Aucun commentaire:

Enregistrer un commentaire