Using the repository pattern with Entity Framework (mvc storefront) Using the repository pattern with Entity Framework (mvc storefront) asp.net asp.net

Using the repository pattern with Entity Framework (mvc storefront)


Let me answer your questions one at a time:

Your repositories should return IQueryable<T>, not ObjectQuery. The reason is that the whole purpose of the repository pattern is to abstract away the specifics of your data store. This allows you to do things like substitute a mock repository when you unit test your controllers. If you make the repository return ObjectQuery, then you are not abstracting away the Entity Framework. Another way of saying this is the users of your repository should not know, as much as possible, that it is the Entity Framework which is doing the O/R mapping.

In order to use the greater than and less than symbols in paragraph text in Stack Overflow, you must escape them as you would in HTML, i.e.:

<

You do not need to do this in a code block; in code blocks, you just type the less than/greater than symbol.


Maybe if you see the Contact Manager Tutorial in the http://www.asp.net/learn/mvc/#MVC_SampleApp site, they use the Repository Pattern and the Entity Framework.


I started like you a few weeks ago, you will see it's pretty easy to work with EF. My project is small so i'm using the entities generated by the EF as my model classes, and you can add your own logic to them using a partial class.

Here's a simple method of one of my repositories, as a example:

    /// <summary>    /// Finds a user by it's credentials    /// </summary>    /// <param name="oUser"></param>    /// <returns></returns>    public User FindByCredentials(string username, Byte[] password)    {        User user = null;        if (!Validators.IsStringEmptyOrNull(username))        {            user = this.FindByCredentialsQuery(username, password).FirstOrDefault<User>();        }        return (Validators.IsNull(user)) ? new User() : user;    }    /// <summary>    /// Finds a user by it's credentials    /// </summary>    /// <param name="username"></param>    /// <param name="password"></param>    /// <returns></returns>    protected IQueryable<User> FindByCredentialsQuery(string username, Byte[] password)    {        var query = from Users in this.UserDataContext.Users                    where                        (Users.Username == username) &&                        (Users.Password == password) &&                        (Users.Enabled == true)                    select Users;        return query;    }

Note that i'm using IQueryable only inside the repository, and return only the list of entities requested. This way i can control that the query to DB is always executed inside the Repo.