Skip to content

Instantly share code, notes, and snippets.

@dnasca
Last active August 29, 2015 14:18
Show Gist options
  • Select an option

  • Save dnasca/b1f04e8efd594d2a891a to your computer and use it in GitHub Desktop.

Select an option

Save dnasca/b1f04e8efd594d2a891a to your computer and use it in GitHub Desktop.
Creating a Data layer - 3b.) Repository - Building the implementation that will provide data access to the dB
/*
This is where all of the steps are tied together.
After we complete this class, we will simply supply the Repository (which wraps the Context) directly to the
Controllers constructor method as a parameter.
--For example. After we complete the class below, the Controller might look something like this:
public class HomeController : Controller
{
private INoteRepository _repo;
public HomeController(INoteRepository _repo)
{
_repo = repo;
}
}
We could then access the data with something like this on an ActionResult:
var topics = _repo.GetTopics()
.OrderByDescending(t => t.Created)
.Take(10)
.ToList();
return View(topics);
The most important part of this class will be to follow the dependency injection that happens on the constructor.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Note.Data
{
public class NoteRepository : INoteRepository
{
NoteContext _context;
public NoteRepository(NoteContext context)
{
_context = context;
}
public IQueryable<Topic> GetTopics()
{
return _context.Topics;
}
public IQueryable<Reply> GetRepliesByTopic(int topicId)
{
// this Where clause will return an IQueryable object, with an ID attached to it
return _context.Replies.Where(r => r.TopicId == topicId);
}
public bool Save()
{
try
{
return _context.SaveChanges() > 0;
}
catch (Exception ex)
{
return false;
}
}
public bool AddTopic(Topic newTopic)
{
try
{
_context.Topics.Add(newTopic);
return true;
}
catch (Exception ex)
{
return false;
}
}
public IQueryable<Topic> GetTopicsIncludingReplies()
{
return _context.Topics.Include("Replies");
}
public bool AddReply(Reply newReply)
{
try
{
_context.Replies.Add(newReply);
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment