Entity Framework – Separating Business Logic from Model with Repository

asp.netcdesign-patternsentity-frameworkrepository

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.

Best Answer

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.