EF and Repository Pattern
I am writing a project in MVC and am using EF 4.0. I am using the repository pattern but am unsure about where to place some properties.
public interface IUserRepository<User>
{
User GetUserById(int userId);
void UpdateUser(User user);
void AddUser(User user);
List<User> GetUsersByName(string userName);
void Create(User user);
int NumberOfFollowers { get开发者_开发知识库; set; }
}
My two problems are 1). should the property NumberOfFollowers
be a property or a method?
and 2). should it be placed inside the User entity class instead of the interface?
cheers.
If NumberOfFollowers
is a property of a User, it should definitely be on the User
class, not the repository. The repository is responsible for getting/putting data only.
Here is my favorite repository implementation for EF:
http://www.codeproject.com/KB/database/ImplRepositoryPatternEF.aspx
This one is terrific, very complete and comes with a lot of features.
re: property or method, .NET Design Guideless dictate that it shouldn't be a property if it could a) throw and exception or b) take a noticeable amount of time to return.
NumberOfFollowers
would be a property of the User itself and not in the repository interface.
I will agree wilth Daniel's answer - having a property named NumberOfFollowers
would be most logical. As a guide, if there is data you can access via the User
object itself, then have properties\methods created directly on the User
class. Oftern if you have foregin keys to other tables, then accessing those data items can be done via the User
class and should be encapsulated inside properties\methods.
On the other hand, if you wanted to find information relating to a User
, but would require another object's help, then create a UserService
class. Keep the repository simple - have data retrieval\manipulation methods only, and created more involved/business logic hungry methods in a seperate service class e.g.
public class UserService {
private DbContext Context {get; set;}
public IList<Document> GetUserDocument(User user)
{
// Assuming User table does not have a Document ID as a foregin key..
// Do whatever you need to do to get document.
} }
The above is rough guide and by no means the defacto standard, but it works well for me.
I wrote a blog about it and covered how to abstract ORM provider specific features, per request object context management, managing models from multiple databases, Transaction Management with Unit of Work Pattern with complete source code and examples.
Please take a look and let me know if you have any questions.
精彩评论