Implementing repository for EF4 using DDD and IoC

前端 未结 2 2061
野的像风
野的像风 2021-01-06 00:00

I think I\'m going in circles.

I\'m working on an MVC 3 solution using EF4 & POCOs (database-first) and IoC. My repository and UoW patterns were mostly adopted

2条回答
  •  忘掉有多难
    2021-01-06 00:19

    This is subjective/matter of opinion, but you could make your Repository return IQueryable, then you can do your "complex queries" in your service like this:

    return _repository // IRepository
              .Find() // IQueryable
              .Where(someComplexPredicate) // IQueryable
              .SingleOrDefault(); // T
    

    ObjectSet : IQueryable, which makes this possible.

    If you want to start doing ObjectSet-specific things in your service, you've got two options:

    1. Expose the ObjectSet-specific method as a method on your Repository interface
    2. Use an IQueryable extension method to do a "soft cast" to ObjectSet (e.g var objSet = source as ObjectSet).

    Always try and go with option 1.

    Perfect example is eager loading. There is a method called Include on the ObjectContext, so if you use IQuerayable in your Repository, how do you eager load?

    Since Include takes a "magic string", you could accept this in your Find method on your Repository, e.g:

    return _repository // IRepository
              .Find("Product.Orders") // IQueryable
              .Where(someComplexPredicate) // IQueryable
              .SingleOrDefault(); // T
    

    Fortunately in EF CTP5 they have introduced a strongly-typed Include which works off IQueryable, so i didn't have to do the above when i cutover.

    So as i said, best thing to do is expose methods on your Repository interface. But there needs to be a tradeoff - an interface should be a "contract" or "definition" of a service, not about the implmentation. So EF-specific things should be done via extension methods. General things can be done via the repository interface.

提交回复
热议问题