使用纯 POCO 实体框架在存储库模式中获取策略示例
我正在尝试使用实体框架和存储库模式推出一个策略模式,使用一个简单的示例,例如 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)
}
我的基本问题是这个问题中提出的问题。我希望能够使用策略模式获取没有帖子的用户和有帖子的用户。
I'm trying to roll out a strategy pattern with entity framework and the repository pattern using a simple example such as User
and Post
in which a user has many posts.
From this answer here, I have the following domain:
public interface IUser {
public Guid UserId { get; set; }
public string UserName { get; set; }
public IEnumerable<Post> Posts { get; set; }
}
Add interfaces to support the roles in which you will use the user.
public interface IAddPostsToUser : IUser {
public void AddPost(Post post);
}
Now my repository looks like this:
public interface IUserRepository {
User Get<TRole>(Guid userId) where TRole : IUser;
}
Strategy (Where I'm stuck). What do I do with this code? Can I have an example of how to implement this, where do I put this?
public interface IFetchingStrategy<TRole> {
TRole Fetch(Guid id, IRepository<TRole> role)
}
My basic problem was what was asked in this question. I'd like to be able to get Users without posts and users with posts using the strategy pattern.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我们谈论策略模式,那么 IFetchingStrategy 必须传递给 IUserRepository 所以我认为你应该修改 Get 操作:
但我不确定如何使用 EF 实现此类接口。
如果我们回到你之前的问题,它也可以通过这种方式完成:
你将这样使用该方法:
但我猜这个实现仅适用于第一级导航属性。
If we talk about strategy pattern then IFetchingStrategy must be passed to IUserRepository so I think you should modify Get operation:
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:
You will use the method this way:
But I guess that this implementation works only for first level of navigation properties.
下一篇文章中的答案使用策略模式来操作查询。
https: //codereview.stackexchange.com/questions/3560/is-there-a-a-better-way-do-dynamic-filtering-and-sorting-with-entity-framework
An answer in the following post uses strategy pattern to manipulate a query.
https://codereview.stackexchange.com/questions/3560/is-there-a-better-way-to-do-dynamic-filtering-and-sorting-with-entity-framework