What is proper abstraction using Entity Framework in webforms - asp.net

I am trying to figure out a good way to architect my solution. I know that I am going to be using the following technologies, Asp.Net Webforms, and Entity Framework 4.1. My EF model is based on an existing database. I'm planning to use the EF DbContext generator to build my context and entities. And this is the point where things get a little tricky for me.
I want to have proper separation of concerns, providing for better testability and allowing me to separate my business logic from my DAL. I have three projects in my solution currently: Web, Core, and Data. I would like dependencies to be Web -> Core <- Data, with no dependency between Web and Data at all. This requires my entities to actually exist in Core, rather than Data (where my edmx is). Currently, my thought is to move the Entities.tt file to Core and change the inputFile to point to my edmx in Data to generate my Entities in Core. But I'm unsure what to do with the Context. It's heavily dependent on EF and therefore I don't simply want to move that into Core. I thought about interfacing it, creating my own IEntities.Context.tt and dropping that in Core. My concern is the loss of functionality if my interface doesn't create DbSets and DbContext.
Two thoughts I've been having on this are, 1) put a ref to System.Data.Entity in Core, 2) don't use DbSet and replace it with ICollection (or some such generic container) and wrap DbContext as just an Object in my interface.
Any insight would be very appreciated. Thank you.

There are lots of different patterns you could use, but two come to mind immediately:
1) Add a business / service layer - this will abstract between your data layer and your presentation layer. This is the approach I take most often - using AutoMapper and Dependency Injection (I like Ninject) to make the monkey work easier. Your business layer would expose either its own version of your database objects (not recommended), or objects which related to your business model (a more robust approach).
2) Use the Inversion of Control pattern - Very popular at the moment, though I'm yet to give it a bash in a real life scenario. Apparently very good for TDD / mocking etc... it basically means that your data layer has a dependency on your business layer instead of the other way around.
FYI - My "Core" or "Common" assemblies know nothing about my business or data layers - they merely provide platform agnostic helpers and common classes - if I want to create common MVC functionality, for example, I'll create a Company.MVC.Core assembly instead.

If your solution is completely greenfield then I like to use a code first approach in entity framework (forgive the shameless plug but I've put a tutorial on my blog about this http://www.terric.co.uk/code-first-entity-framework-and-sql-migrations/). I like the control it gives me that I can't seem to get when I generate a .edmx.
Moving onto structure, I usually separate the layers of my project into separate assemblies: Domain (and Data) and WebUI structured with the following folders (namespaces):
Domain (business layer and data layer assembly)
Data (contains my EF data context and Interface to the context)
Entities (contains my POCO objects for the context)
WebUI (presentation layer assembly)
Infrastructure (contains my dependency inject initialiser)
I never DI my entities and instead use the concretes in my presentation layer, however the context I'll always DI as I may want / have to use ADO.Net (especially for legacy apps) where my Domain layer will still use ADO.Net to read / write my POCO entities. This way, when I eventually get scope to implementing an ORM with my legacy app I can simply DI the ORM version of my Domain.
As a footnote to this, if you were following the repository pattern you could always interface them and DI your repositories. Either way, your POCOs should be specific to the solution so the underlying data structure doesn't dramatically change often hence I never DI them.

Related

Separate ASP.NET Project references when using DI (Autofac) and Identity

I want to separate my ASP. NET MVC 5 + WebApi2 solution into separate logical projects, so (in my head) I have:
Data.csproj
references EF6 and handles Code First migrations
Models.csproj
references Automapper
refrences Data (above)
Services.csproj
references Models (above)
Web.csproj
references autofac
references services above
But I can't get my real project to look like that because
Identity sprinkles the model and EF references all over my Web.csproj
When I configure Autofac in Web.csproj and try to register my DbContexts and whatever other dependencies are in my other projects, I will need access to the concrete types, so Web will need to reference all other projects as the DI is setup in Web?
This is a brand new project auto-generated by the ASP .NET template. Thanks.
Generally, you avoid getting your Entity-Framework pollution into your web code by not referencing your data-models in your web project.
If you put interfaces for the models in a separate infrastructure project, for example, you won't have that problem any more. Your 'services' can return abstract types with no dependency on EF and coupling is reduced.
Personally, I like to get around this problem wither with a separate project that is responsible for factory code or (even better IMO) giving each project responsibility for constructing its own objects. Having the factory code in the same place further reduces coupling and can make refactoring easier.
One more thing...
If this is a new project, why do you even need a DI container. You could always use poor man's dependency injection and refactor later when you have a better idea of your needs. They are often overused or used as a crutch to hide overly complex lasagna code. It is an incredibly useful and powerful technology, but most of the benefit in terns of flexibility can also be realised through well designed factories and builders. These can have the additional benefit of increased readability.

Advice on refactoring Business/Data Logic in preparation for migrating WebForms to MVC

I'm looking some advice on to a strategy for migrating from Asp.Net WebForms to MVC. I currently have a solution of approx 60 projects in the following format:
Solution
ProjectA.DataModel
ProjectA.Business
ProjectA.Web
ProjectB.DataModel
ProjectB.Business
ProjectB.Web
Framework.Core
Framework.Common
…etc
All data models are Entity Framework 6 using database first (.edmx) and T4 templates. Data access code is mixed between both the Business and Web (WebForms) projects. The code base has grown organically initially from a sole developer through to a small team which explains some of the bad practice in terms of SOC however we want to try take this opportunity to rectify this.
I want to start moving towards a full MVC solution and feel the first thing to do is ensure any data access logic currently residing in the Web projects is pushed to the Business layer to get Separation of Concerns. Researching into a best practice for this has taken me towards the Unit of Work and Repository patterns however further reading seems to be suggesting this is overkill.
What would be the best approach to refactoring my Business and Data Layers with the current Web Forms model in readiness for MVC. Secondly is an accepted approach for migration to MVC to bring in Views to the existing WebForms solution to create a Hybrid or to create a new MVC project, reference my existing BAL and DAL and start building the application UI from scratch?
In regards to Entity Framework, everything appears to be moving towards a CodeFirst approach. Is this something we need to be planning for if we want to go forward with a best practice approach?
We are currently a very small team and want to try make best possible re-use of our existing projects and refactor as much as possible to get into a position of beginning to move towards MVC.
Any thoughts on how I can begin to approach this is appreciated.
Thanks
Nasty app you have there. Anywas, first thing to rembmer is that MVC is a UI pattern. So in a properly designed app the swtich from WebForms to Mvc would mean just change the UI layer.
I want to start moving towards a full MVC solution and feel the first thing to do is ensure any data access logic currently residing in the Web projects is pushed to the Business layer to get Separation of Concerns
No! Data access logic should be in the DAL (hint: it's an acronym), not BL, not UI. Persistence Only. BL and UI would ask the DAL to save/retrieve their objects via Repository. And btw, EF deals with db only. Don't make the mistake to build your business objects on top of Ef Entities. One models business concept and behaviour, the other model database access. They're usually not compatible. When dealing with anything but persistence, ignore that you have a db or an ORM.
Researching into a best practice for this has taken me towards the Unit of Work and Repository patterns however further reading seems to be suggesting this is overkill.
It's overkill ONLY if you a have a very simple app that you don't care about maintaining it. I know is hard to believe but probably over 80%(more or less random number) of devs still don't understand how to properly implement the Repository pattern that's why it becomes useless for them. In a nutshell, the repo uses the EF but it's not built on top of it. The repo 'transforms' business/ui objects to EF entities and vice versa.
The repo interface should never expose IQueryable or the fact that you're using a db in the first place. So, no generic repositories and no exposing of EF entities. Also, the Bl/UI shouldn't create queries (it would mean they know how the data is stored - a DAL implementation detail), that's the repository's job. THe higher layers just tell the repository what they want, never how to do it.
Secondly is an accepted approach for migration to MVC to bring in Views to the existing WebForms solution to create a Hybrid or to create a new MVC project, reference my existing BAL and DAL and start building the application UI from scratch?
Although you can mix WebForms and Mvc in the same project, it's better not to do it (less headaches). Start the mvc app from scratch then port the web forms pages to it.

ASP.NET MVC Application Design

Ok, So I have been taking in all sorts of great information about MVC, EF4, Repository Pattern, UoW, Service Layers, etc and now I am going to attempt to put it all together.
My question is, How should these be separated?
I was thinking projects like this:
1) Application - MVC App
2) Repository Layer
3) Entities - EF4/Partial Entity Classes
Any suggestions would be great!!
Thanks,
Sam
Here's one example of how you could structure your application:
Domain Models (Primary POCO objects)
Repositories (Implementation of some data access technology depending on the project requirements : EF, NHibernate, LINQ to XML, Remote web service calls, ...)
Service (business operations aggregating multiple CRUD operations into a business operation that will be exposed with the domain objects)
ASP.NET MVC application (Controllers, Views, View Models, Mappers between the Domain objects and the view models)
This layers could represent a physical separation (assemblies) or logical separation into the same assembly.
Don't separate code physically until you have a physical reason to do so such as deployment or code sharing reasons. Use folders and namespaces.
I've just been through this myself and by far the best approach i found is S#arp Architecture.
Excellent templates generate the project scaffolding for you and they have a good explanation why u really do want physical project separation. Good argument here. Theyre tutorial shows how TDD with this model is a breeze.
The beauty of this model is the separation of concerns it offers so if you did want to use EF, its a snip to swap out NHibernate.

Is it a bad idea to do ASP.NET MVC without any ORM?

I am learning ASP.NET MVC now a days and I have found that most of the examples in ASP.NET MVC are with ORM. I don't have any issue in using ORM for my learning and personal project. But at my work we have worked only with ASP.NET web forms and we use stored procedures only. We have data access layer (simple c# classes) as interface between asp.net code behind page and stored procedures. Now if we want to use ASP.NET MVC, will it be a bad idea to do it without an ORM. As most of the MVC frameworks like rails/django have built-in ORMs, is it any harm to use our own data access layer with ASP.NET MVC. I don't want to have any database related activity like datareader, datatable in my controllers. Is there any other better solution?
If you have a DAL already built - use it! Unless you were planning on moving from your existing DAL to an OR/M anyhow you won't find it beneficial to move to an OR/M for it's own sake.
One of the beautiful things about the MVC pattern is the is encourages a separation of concerns. This means that you are reducing coupling in you application which makes your application's architecture flexible and modular. This means that if at some point you want to swap out your existing DAL for a more modern OR/M solution you can do so with minimum impact to your application.
No harm at all. ASP.NET MVC doesn't require ORMs but you should have models (that might not map to your stored procedures 1:1) of the data your views and controllers can deal with.
You can roll your own ORM if you like even. ORMs are around to make things quicker for development so that you can easily map your database data to object models that you use in your application. You can map ORMs to stored procedures as well.
I personally perfer to use stored procedures and map the results to object through my own data access layer as it gives me a lot of flexibility. This is a personal preference though and there is no right / wrong answer.
Model View Controller is a framework to help provider a clear separation of concerns between the tiers of an application. The Model can be any form you wish really. ORM is not always appropriate, if you have some other DAL in mind then use it. Direct data access with the repository pattern works well, this will help you hide the logic you do use to access your database and allow you to change it later down the track with much more ease.

I need some clarification on the MVC architecture and the three-tier architecture

I've been reading the book Pro ASP NET MVC Framework and I'm getting really confused with a lot of things. I've been trying to do some research but I'm finding that with so many different approaches and concepts being thrown at me, it's just making things worse.So I have a few questions:
I know MVC is supposed to split the functionality into three main things: Model -> Controller -> View. Is the MVC a different approach than the three-tier architecture? Or am I still supposed to be thinking of creating a Data Access Layer and a Business Logic Layer in my project?
What exactly are Repositories? It is what acts as my Data Access Layer? Where/How do Repositories fit into the MVC?
The book talks about using LINQ to SQL to interact with the database but yet it states that LINQ to SQL will not be supported in the future and that Microsoft is dropping it for the Entity Framework. Where does the Entity Framework fit into the MVC and how do I interact with it?
Thanks in advance for your help!
Matt
MVC is mostly a pattern for the presentation layer, and it focuses on the interaction between the view and the controller. The model can be considered to be the components of the application that are responsible for maintaining state, including persistence.
In a simple application the model might just be an LINQ-To-SQL model. In a large enterprise application the model might contain a data access layer, business layer, and a domain layer. The ASP.NET MVC does not restrict you to how the M should be implemented.
The Repository pattern is one way to implement the persistence part of the M. The ActiveRecord is another. Which pattern to choose depends on the complexity of the application, and your preferences.
Take a look at Step 3 of the NerdDinner tutorial where they create a simple repository using Linq to SQL.
Linq to SQL will not be dead. Microsoft will still improve the core and add customer requests where it makes sense but Entity Framework would be the primary focus. Take a look at this post for LINQ to SQL changes in .NET 4.0.
The EF can be used is a similar way as LINQ to SQL, but it is also more flexible so it can be used in other ways. For example EF4 will more or less support persistence of your own POCO objects in a more Domain Driven Design.
Yes, I think MVC is a different approach than "the" 3-tier architecture that I think you meant here (the architecture where you create mainly 3 projects DAL, BL, and UI). The main idea behind MVC is the separation of concerns between each of its components (Model, View and Controller). The controller is the component responsible for handling user requests, and in most cases it corporates with the "Model" component in order to display the desired view as a response to the user request. The difference between this and the traditional 3-tier architecture, is that the DAL, and the BL are grouped now and named a Model and yes you still need to create these components.
What are repositories?
Martin Fowler mentions the definition of a repository as "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects" Repositories are part of your data access layer, they don't access data by themselves, they mediate between the domain and the data mapping entities, and of course they should be placed in your Model folder/project.
Will Linq to SQL be deprecated?
NO and the same book states so, also Damien Guard ( a developer at the ADO.NET team) mentioned in one of his blog posts that Linq to SQL will be included in .NET 4.0.
How to interact with EF?
As you would with Linq to SQL. Like Linq to SQL, Entity Framework will be your mapping entities, and will reside in the Model project as well.
Hope this helps!
I guess you're a bit confused over these things, and they are confusing, so let's go over them slowly.
N-Tiered Architecture and MVC are different, but intertwined. N-Tier usually talks about separating Data Access, Business Logic and the User Interface. However, some people may argue that it is impossible to totally separate BLLs from the UI; MVC addresses that, in such a way that there is a corresponding Controller talking to your BLL, and to your View, as opposed to having your View talk directly to your BLL.
Yes, having repositories is one approach to having a DAL. There are many ways of doing this, and you should not limit yourself to what is discussed in the book.
The book only uses LINQ to SQL to demonstrate ASP.NET MVC the fastest way possible, but it is NOT the only way. Stop thinking about LINQ to SQL for a minute; ASP.NET MVC can be used whether you use an ORM like NHibernate or you use plain ADO.NET + DAL Factory or whatever -- what you'll not going to be able to use are those ASP.NET ObjectDataSources that you drag and drop with your UI.
As for Entity Framework, Brad Abrams wrote a nice guide on how to use Entity Framework with ASP.NET MVC, that should cover your last question.
HTH
Yes you still need to create data access and business logic layers yourself. Some may argue that the Controller layer IS the business logic but I personally prefer the separation between real business logic (e.g. pricing calculation) from screen business logic (e.g. event handler for the "OK" button). You will then call these from your Controller class. The controller class controls the logic for your screen and manages the translation from your data/business logic layer to the screen value.
the ASP.NET MVC framework puts no restriction on the "Model" layer, which means you can use whatever you want including NHibernate, LINQ to SQL or entity framework. I use LINQ to SQL because it's simple.
Not sure, never read that book. I just downloaded Scott Hanselman's Nerddinner project from codeplex and use that as a guide for writing ASP.NET MVC websites.

Resources