Repository Pattern without LINQ or other ORM?

Deadly 提交于 2019-12-04 04:24:31

问题


Does it makes sense to use the Repository pattern without the use of LINQ or some other ORM? I am writing an application in MONO and using MySQL, was thinking of using the repositoy pattern but not going to be able to deal with IQueryable. I was thinking of just exposing more methods on the repository to make it obvious that filtering was going to happen on the db side with the repository call. Any suggestions if that is a valid use of the design or any other design ideas instead?


回答1:


Repository has nothing at all to do with IQueryable. What you are thinking of is the Rob Conory .net 3.5 take on the repository pattern, which is actually more of a data broker pattern.

A repository is responsible for returning objects, and deals with data access so that the rest of your application can remain ignorant of it.

You can see a very high level description on Martin Fowlers site




回答2:


It's absolutely possible. But you should move queries to repository site and implement one repository per class. For example:

public abstract class GenericRepository : IRepository {
    public virtual T Get<T>(Identity id) where T : PersistentDocument {
        using (IDbConnection connection = GetConnection())
        using(IDbCommand command = CreateGetCommand(id, connection)) {
            using (IDataReader reader = command.ExecuteReader()) {
                var mapper = DaHelper.GetMapper<T>();
                return mapper.Map(reader);
            }
        }
    }

    protected virtual IDbCommand CreateGetCommand(Identity id, IDbConnection connection) {
        IDbCommand command = connection.CreateCommand();
        command.CommandText = String.Format("SELECT * FROM {0} e WHERE e.id = ?", TableName);
        command.Parameters.Add(id.ToGuid());
        return command;
    }

    protected abstract string TableName { get; }
}

public class UserRepository: GenericRepository<User>, IUserRepository
{
    protected override string TableName { get { return "users"; } }

    public User GetByEmail(string email)
    {
        using (IDbConnection connection = GetConnection())
        using (IDbCommand command = connection.CreateCommand())
        {
            command.CommandText  = String.Format("SELECT * FROM {0} e WHERE e.email = ?", TableName);
            command.Parameters.Add(email);
            using (var reader = command.ExecuteReader())
                return DaHelper.GetMapper<T>().Map(reader);
        }
    }
}



回答3:


Sure. The repository is simply a pattern used by linq. You can provide any sort of data access you want through it. A project I work on uses repositories that deal with strongly typed DataSets.



来源:https://stackoverflow.com/questions/446629/repository-pattern-without-linq-or-other-orm

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