2

I am working on my first public-facing web application and I’m using MVC 4 for the presentation layer and EF 5 for the DAL. The database structure is locked, and there are moderate differences between how the user inputs data and how the database itself gets populated. I have done a ton of reading on the repository pattern (which I have never used) but most of my research is pushing me away from using it since it supposedly creates an unnecessary level of abstraction for the latest versions of EF since repositories and unit-of-work are already built-in.

My initial approach is to simply create a separate set of classes for my business objects in the BLL that can act as an intermediary between my Controllers and the DAL. Here’s an example class:

public class MyBuilding
{
    public int Id { get; private set; }
    public string Name { get; set; }
    public string Notes { get; set; }

    private readonly Entities _context = new Entities(); // Is this thread safe?
    private static readonly int UserId = WebSecurity.GetCurrentUser().UserId;

    public IEnumerable<MyBuilding> GetList()
    {
        IEnumerable<MyBuilding> buildingList = 
            from p in _context.BuildingInfo
            where p.Building.UserProfile.UserId == UserId
            select new MyBuilding {Id = p.BuildingId, Name = p.BuildingName, Notes = p.Building.Notes};
        return buildingList;
    }

    public void Create()
    {
        var b = new Building {UserId = UserId, Notes = this.Notes};
        _context.Building.Add(b);
        _context.SaveChanges();

        // Set the building ID
        this.Id = b.BuildingId;

        // Seed 1-to-1 tables with reference the new building
        _context.BuildingInfo.Add(new BuildingInfo {Building = b});
        _context.GeneralInfo.Add(new GeneralInfo {Building = b});
        _context.LocationInfo.Add(new LocationInfo {Building = b});
        _context.SaveChanges();
    }

    public static MyBuilding Find(int id)
    {
        using (var context = new Entities())  // Is this OK to do in a static method?
        {
            var b = context.Building.FirstOrDefault(p => p.BuildingId == id && p.UserId == UserId);
            if (b == null) throw new Exception("Error: Building not found or user does not have access.");
            return new MyBuilding {Id = b.BuildingId, Name = b.BuildingInfo.BuildingName, Notes = b.Notes};
        }
    }
}

My primary concern: Is the way I am instantiating my DbContext as a private property thread-safe, and is it safe to have a static method that instantiates a separate DbContext? Or am I approaching this all wrong? I am not opposed to learning up on the repository pattern if I am taking the total wrong approach here.

6
  • 2
    In my experience, you can new up a DBContext on each repository call without too much penalty, and you won't have to think about thread safety at all if you do. The DBContext object is meant to be relatively lightweight. Commented Oct 27, 2013 at 1:50
  • Thanks Robert. So what would be the difference if I called a new DbContext from a Repository vs. calling it straight from my business object class as I have now in my code?
    – bnice7
    Commented Oct 27, 2013 at 2:03
  • The repository is there to provide a level of indirection between your database and your service layer or business logic layer. But EF may already be providing that for you. See martinfowler.com/eaaCatalog/repository.html and ayende.com/blog/4784/… Commented Oct 27, 2013 at 5:31
  • Maybe you could rethink using EF and use something more lightweight like Dapper? ( code.google.com/p/dapper-dot-net ) The argument is, that EF (and ORM in general) adds tons of complexity. And if you can't map it nicely to DB, then it will be real pain in the ass later.
    – Euphoric
    Commented Oct 27, 2013 at 8:59
  • The reason I chose EF in the first place is primarily because the database structure is out of my control, having been developed by a separate group. They can manipulate it, but I can't. The idea of them making schema modifications and me having to re-write a bunch of SQL to accommodate changes is exactly what pushed me to use an ORM. Instead, I can regenerate POCOs and adjust my domain classes as necessary (still a pain in the ass, though). Dapper is enticing for performance and I realize there are other ORMs out there but we are not looking at a very large user base.
    – bnice7
    Commented Oct 27, 2013 at 15:21

1 Answer 1

3

Because the database schema is both out of your scope and liable to change, it is extra important that you isolate it from your main code base. The mapping and table manipulation operations you are calling from your Create and GetList functions and should ideally live in your DAL. That way, your entities and business logic classes will be unaffected by unexpected changes to EF generated code. Even major changes to the database schema then become merely a matter of changing the mapping functions.

Other that that, I would avoid having business entity instances that have calls to load other instances of their own type - it smells of single responsibility principle violation, as your MyBuikding instances are both data finder objects and data entities. You could get your entities directly from calls to your DAL repositories, or via some intermediate service layer calls if you will require business logic.

1
  • Thank you. I knew something didn't look right with the static method. I will heed your advice and move this logic into the DAL.
    – bnice7
    Commented Oct 28, 2013 at 13:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.