1

我正在尝试使用一个简单的示例(例如用户有很多帖子)来推出具有实体框架和存储库模式的策略User模式Post

从这里的答案中,我有以下域:

public interface IUser {
  public Guid UserId { get; set; }
  public string UserName { get; set; }
  public IEnumerable<Post> Posts { get; set; }
}

添加接口以支持您将在其中使用用户的角色。

public interface IAddPostsToUser : IUser {
  public void AddPost(Post post);
}

现在我的存储库如下所示:

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

策略(我被困的地方)。我该怎么处理这段代码?我可以举个例子来说明如何实现这个,我在哪里放这个?

public interface IFetchingStrategy<TRole> {
  TRole Fetch(Guid id, IRepository<TRole> role)
}

我的基本问题是这个问题中的问题。我希望能够使用策略模式获得没有帖子的用户和有帖子的用户。

4

2 回答 2

1

如果我们谈论策略模式,那么 IFetchingStrategy 必须传递给 IUserRepository 所以我认为你应该修改 Get 操作:

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

但我不确定如何用 EF 实现这样的接口。

如果我们回到你之前的问题,也可以这样完成:

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);
    }
}

您将以这种方式使用该方法:

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

但我猜这个实现只适用于第一级导航属性。

于 2011-01-17T11:48:50.453 回答
0

以下帖子中的答案使用策略模式来操作查询。

https://codereview.stackexchange.com/questions/3560/is-there-a-better-way-to-do-dynamic-filtering-and-sorting-with-entity-framework

于 2012-04-06T14:43:41.763 回答