Asp.net mvc, entity framework, Poco - Architecture - asp.net

I have a "small" enterprise application, aspnet mvc 3 + entity framework with POCO entity and repository pattern. I structured the solution in 4 projects:
POCO entities
Domain model
Services
web application
When the application performs a query on the database, use one of the services provided, the service uses the repository and the small classes, as a result I have some dynamic proxy objects that I would like to convert in my domain entities, before using them in mvc views, but I do not know how. Dovrebber be set as the translator?
This approach is reasonable?

AutoMapper is handy for converting objects from one type to another. It will generally "do the right thing" if all your destination type properties have correspondingly named source type properties, and any nonmatching properties can easily be mapped manually using lambda expressions.

Not sure what the "small classes" being used are, but I assume you will want to use some IOC to be able to inject your repository into the service layer. See more here: http://msdn.microsoft.com/en-us/magazine/dd942838.aspx#id0420033

Related

What is proper abstraction using Entity Framework in webforms

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.

WCF + Entity Framework design

I was wondering how to design this best..
On my ASP.NET MVC application I have a database and I want to use a WCF to handle all my interaction with that database through EF. So I've create a Entity Model on the service which I use to interact with the database. In order to interact with the WCF from the ASP.NET app I've created DTO's for each EF model (I only have 3) and a Converter class to convert from the EF models to the DTO's and vice versa.
On a side-note.. would it be possible to avoid using DTO's and just transfer the EF models instead? - I've tried, but with no luck as the client asp.net app doesnt recognize these models.
Is this a suitable way of designing this or would another approach be better?
Thanks in advance. :)
This architecture is indeed used in situations where business logic and data access logic is deployed on another server then asp.net frontend. Reason for such architecture can be company policy, security, scalability, etc. But usually it is for bigger projects.
You said that you have 3 "EF models". Does it mean that you have 3 EDMXs files or 3 entities? If you mean 3 entities than your project is probably very small and unless you really must use this architecture (direct requirement) or unless you are doing just some test project there is no reason to do that.
How do you use DTOs? Is it just (or very close) 1:1 mapping to EF entity? In such case you missed DTOs purpose and you most probably don't need them. If your service exposes CRUD operations you can use EF entities directly (but you must use POCO or STE).
Moreover if you just want to expose EF model as CRUD service you should check WCF Data Services.

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.

How to sort this Repository pattern and ASP.Net website architecture?

I am Creating a new ASP.Net website "not mvc", and willing to make the data access layer has 2 versions, one using the Linq to Sql and another one using ad.net entity framework.
Note: kigg is doing the same but in MVC website and too complex than i want.
I learned that the best pattern to achieve my goal is using repository design pattern.
My question is, where in my code and layers "dal, bal, ui" the switch will happen? in other words where i will change the code to apply the linq to sql to ado.net entity framework or vice versa.
I wrote:
IRepository repository;
Then in the class constuctor
repository = MyRepositoryLinqToSql();
can some one teach me this part architecture wise?
If you want to create a pluggable architecture to be able to swap out the repository layer on the fly then you will need to create everything behind an interface and then use something like StructureMap to dynamically swap in what you need when you need it.
You would want to define a repository class like AccountRepository. One for linq to sql LSAccountRepository and EFAccountRepository. Both of these would inherit from IAccountRepository and have methods such as GetAccountByID, SaveAccount, DeleteAccount, etc.
Then using StructureMap you would have syntax like so to load the appropriate repository based on the system that you are loading in.
IAccountRepository _accountRepository = ObjectFactory.GetInstance();
Then via your configuration you can specify the default implementation of IAccountRepository and swap this out to point to either implementation at any time.
If this is too complex then a dependancy injection patten can be used in that you can have a method with a parameter of IAccountRepository. This method would be called by a controller (MVP or MVC) and you can pass in the appropriate reference at that time. This way you do not directly instantiate the repository inside of the method that might need one repository vs. another.
Even if you do decide to do a DI pattern you can still use StructureMap. When you instantiate an object that has other dependancies in it that StructureMap knows about (in the constructor) then StructureMap will also load up those objects as well. Then the caller of the object that has the method that you need will be the only loose coupling that is needed as StructureMap will dynamically take care of the dirty work for you.
This is a bit of a heavy question to answer, but you could add a constructor that takes an IRepository instance as a parameter and use that within the class itself. As for how to populate it, please do some research on Inversion of Control containers such as Spring and Windsor. These tools take configuration details about which specific implementations you want to use and then automatically pass these instances to the constructors and properties of classes.
For example, you can indicate which version of IRepository you want to use in your app.config file, and whereever this appears in a constructor an instance of your chosen class will be passed in.
I think you're looking for "Dependency Injection" solution.
Chack this out:
Unity Dependency Injection Video using ASP.NET Webforms - Ninject and Autofac IoC Too!
Unity And Asp.Net WebForms

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