mara19
mara19

Reputation: 121

Update ASP.NET MVC to use Unit of Work pattern

I am currently changing my asp.net-mvc site to use the unit of work pattern rather than having my controllers access the database context directly, as I've read that it will make testing easier.

I have been following a Microsoft guide and the unit of work class contains the following get method

 public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = dbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        if (orderBy != null)
        {
            return orderBy(query).ToList();
        }
        else
        {
            return query.ToList();
        }
    }

However I'm unsure of exactly what this method does, especially what can be passed in as parameters. I am new to c# and asp.net-mvc so apologies if this is a stupid question, can anyone explain more clearly how this method works it would be great? I am altering my ManageController currently and I have a method which accesses the db directly and would like to change this but I don't know how to call the unit of work get method correctly to access to find the current user and their orders in my Order table. Any help is really appreciated!

  public ActionResult ViewBookings()
  {
      string currentUserId = User.Identity.GetUserId();
      ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id ==   currentUserId);
      List<Order> bookings = (from b in db.Orders where b.user.Id == currentUser.Id select (b)).ToList();           
        ViewBag.Bookings = bookings;
        return View();
    }

Upvotes: 0

Views: 569

Answers (1)

Bon
Bon

Reputation: 1091

Entity Framework already has UoW built in. That is what the SaveChanges and SaveChangesAsync methods are for. It is unnecessary to add anything to it for UoW pattern.

The code you pasted are just queries with conditionally applied filters. Unit of Work pertains to the Create, Update, and Delete portions of CRUD.

If you are wanting to separate your front end from data access, you are looking for CQRS, Command/Query Responsibility Separation. This can be well achieved using a service bus of some kind that the UI consumes to get and modify data on the backend independent of the actual store being used.

Upvotes: 1

Related Questions