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 😉

8

Extending the ORM Context is a good approach, but in a system with lots of predefined queries, I use to take another approach, using Extensions methods in order to group the related queries. Let me give an example:

The usage is kept simple like this:

var data = Context.Financial() // This returns a FinancialContextExtensions instance with all Financial grouped queries
                  .GetComplexReportData() // This returns the actual result for your query
                  .ToArray();

I create a file FinancialContextExtensions:

public static partial class ContextQueryExtensions
{
    public static FinancialContextExtensions Financial(this DataContext context)
    {
        return new FinancialContextExtensions(context);
    }
}

public class FinancialContextExtensions : ContextExtensions
{
    protected readonly DataContext Context;

    public FinancialContextExtensions(DataContext context)
    {
        this.Context = context;
    }

    public IEnumerable<FinancialReportInfo> GetComplexReportData(DateTime dateBeing, DateTime dateEnd)
    {
        return from a in Context.AAA
               join b in Context.BBB on ...
               where ...
               group ...
               select new FinancialReportInfo { ... };
    }
}

PS: I don’t know if this pattern has a name, but a I remember reading it on a site, don’t know what site though…

5

Sounds like you are organizing your code by what the code is and not the domain it applies to. As a developer working with the entity framework, I would expect you to have a derived DataContext class with all your general CRUD operations. Since this DataContext is your gateway to the database, it would make sense to store the queries and methods that use them in your derived class. I suggest not exposing the literal query strings publicly, keep them private and create public methods that use them internally.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật