Fetching Strategy example in repository pattern with pure POCO Entity framework

百般思念 提交于 2019-12-04 19:24:21

If we talk about strategy pattern then IFetchingStrategy must be passed to IUserRepository so I think you should modify Get operation:

public interface IUserRepository 
{   
    User Get<TRole>(Guid userId, IFetchingStrategy<TRole> strategy) where TRole : IUser; 
} 

But I'm not sure how to implement such interfaces with EF.

If we return to your former question, it can also be accomplished this way:

public interface IUserRepository 
{   
    User Get(Guid userId, IEnumerable<Expression<Func<User,object>>> eagerLoading); 
} 

public class UserRepository : IUserRepository
{
    public User Get(Guid userId, IEnumerable<Expression<Func<User,object>>> eagerLoading)
    {
        ObjectQuery<User> query = GetBaseQuery(); // get query somehow, for example from ObjectSet<User>

        if (eagerLoading != null)
        {
            foreach(var expression in eagerLoading)
            {
                // This is not supported out of the box. You need this:
                // http://msmvps.com/blogs/matthieu/archive/2008/06/06/entity-framework-include-with-func-next.aspx
                query = query.Include(expression);
            }
        }

        return query.SingleOrDefault(u => u.Id == userId);
    }
}

You will use the method this way:

User userWithoutPosts = repository.Get(guid, null);
User userWithPosts = repository.Get(guid, new List<Expression<Func<User,object>>>
    {
        u => u.Posts 
    });

But I guess that this implementation works only for first level of navigation properties.

Paul Knopf
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!