Writing a DataContext that talks to multiple controllers with breeze - breeze

Breeze is the best , is Entity Frameworks for javascrpit , and more, but also reduces the calls to database, is so impressive to see it in action (Ctrl-Shift-J).
In the intermediate plural sight SPA video, then changed that uow to be a breezeAPI Uow, which removed the repository factory and provider, very simple http://grab.by/nkU2. everything works awesome http://grab.by/nkUo. got many more ideas from here http://www.breezejs.com/samples/temphire-sample.
now my question,
what about if we need many controllers. so in other words how we have many SPAs in our application, so in the John Papa breeze implementation will means having many datacontext.js.
We may latter need to build a dashboard for employees for example , and then maybe another SPA Dashboard for Products, and so on, so the one controller / one datacontext.js apporach will not be wise
Here is the InvoicingSPA which uses John Papa datacontext.js based on the Open Source Code Camper
http://sdrv.ms/14snOPx
And here is the TempHire v2 in which I added the UnitOfWork (C#) and a Entity Framework Repository to get a nice UOW on the controller
http://sdrv.ms/14snWhY

after working heavily with breeze intellisense i think i found the answer about the easiest way to have 2 or 3 SPAs on the same application
http://www.breezejs.com/sites/all/apidocs/classes/EntityManager.html#method_setProperties
is done very simple in that way
Regards

Related

Breeze with a Unit Of Work/Repository pattern

I was just wondering how I should go about implementing breeze's EFContextProvider in a separate data layer project. Also, since that project is a class library and not an MVC 4 application, how should I include this into my project? I don't really need the whole bag of tricks that is in the Breeze NuGet package, just EFContextProvider stuff. I want to implement a Unit of work pattern using the EFContextProvider DbContext wrapper, like John Papa has done in his wonderful pluralsight course. Has anyone done this yet? any tips?
Thanks
We've got a more sophisticated sample coming called "TempHire" that has a full blown UoW with Repos and separate model projects.
Breeze.NET components (the .NET server-side helpers for a Breeze app ... if you're going with .NET) are all in a single .DLL They have no dependence on MVC at all ... zip. There is Web API stuff in there. Maybe that's what concerns you. Well ... remember that this is open source on GitHub. You are not constrained to the Breeze .DLL. Build your own out of the parts you want.
In my view, the UoW is a short hop from Repository. If you understand what a bounded context is and can translate that to a DbContext implementation, I figure you shouldn't need much help making the transition yourself. There's no magic to it.
For everyone I highly recommend Scott Allen's videos on Repository and UOW in the Pluralsight Design Patterns course ... perhaps the clearest, jargon-free exposition of these patterns I've ever seen.
Here is a post from the Breeze folks about how to use a UoW and Repo on the server with Breeze
http://www.breezejs.com/spa-template#server

Getting Started with Repository Pattern

I'm trying to get started with the repository pattern and ASP.NET MVC, and I can't help but believe I'm missing something. Forgive me if this is a stupid question, but it seems to me like an implementation violates DRY exponentially. For example, in my (admittedly novice) understanding in order to implement this, I would have to:
Create my database model (Currently using Linq to Sql)
Create a IRepository for each concept (table or group of related tables)
Create an implementation for each IRepository
Do we return L2S objects or some sort of DTO?
Create viewmodels which either are containers or copies of the data
Use some method of DI (Windsor or Unity?) on the controllers
While I realize scalability and portability come at an expense, it just feels like I'm missing something?
I tried to implement the Repository Pattern in LINQ 2 SQL and it doesn't work very well, mainly because L2S doesn't use POCOs and you have to map to DTOs all the time as you mention. Although you could use something like AutoMapper, L2S just isn't a very good fit for the Repository Pattern.
If you're going to use the Repository Pattern (and I would recommend it), try a different data access technology such as NHibernate or Entity Framework 4.0's POCO support.
Also you wouldn't create a Repository for each and every table, you create a Repository per Domain Aggregate, and use the Repository to access the Aggregate's Root entity only. For instance, if you have an e-commerce app, with Order and OrderItem entities, an Order has one-or-many OrderItems. These 2 entities are part of a single Aggregate, and the Order entity is the Aggregate Root. You'd only create an OrderRepository in this case, NOT an OrderItemRepository as well. If you want to add new OrderItems you'd do so by getting a reference to the Order entity, then adding the new OrderItem to the Order's Items collection, then saving the Order using your OrderRepository. This technique is called Domain Driven Design, and it's a very powerful paradigm to use if you have a complex Domain Model and business rules in your application. But it can be over kill in simple applications, so you have to ask yourself does the complexity of your Domain Model warrant using this approach.
In terms is adhering to DRY, normally I create a base Repository class that has common methods for Save, Delete, FetchById, that sort of thing. As long as my Repository classes implement this base class (OrderRepository, ProductRepository etc.) then they get these methods for free and the code is DRY. This was easy to do in NHibernate because of POCO support, but impossible to do in Linq 2 SQL.
Don't worry too much about sending your Domain Models directly to the view, most dedicated ViewModels look almost identical to the Domain Model anyway, so what's the point. Although I tend to avoid using the DM for posting data back to the server because of under/overposting security concerns.
If you follow this POCO approach (and ditch LINQ 2 SQL, honestly!!), you end up with only one class (your POCO entity) instead of 3 (L2S class, DTO and ViewModel).
It is possible to implement the Repository Pattern badly, so tread carefully, read a few tutorials, blog posts books etc. (I recommend Steven Sanderson's book, especially look at the Pre-Requisites chapter) But once mastered, it becomes a very powerful way to organise the complexity of hydrating Model objects to and from a data-store. And if you use Repository interfaces (IOrderRepository etc.) and have them injected via an IOC Container, you also gain the benefits of maintainability and unit testability.
Do you understand why your doing these things or are you just following along with a blog article or other source?
Don't implement the Repository pattern because its the new hotness. Implement it because you understand how these separation of concerns helps your project and overall quality of your code.
From your ?'s in your question it sounds like you need to do some more reading before you implement. Your probably missing a meaningful understanding of the overall architecture approach. Please don't take this the wrong way and I'm not trying to be negative.
Side Rant:
Obviously something is missing from the newest repository hotness picture because the confusion about implementation details like single Repository vs. Many/Grouped "DTO or not to DTO" are just so ambiguous and subjective. This is a "nickle question" that pops up again and again.
This has been brought up before, at first glance certain aspects of properly separating concerns does seem to violate DRY.
As you've mentioned MVC have you read Steve Sanderson's Pro ASP.NET MVC 2 Framework book? It spends a great deal of time explaining why using the repository pattern is a good idea.
You might find that, for the projects you're working on, it isn't appropriatte, that's okay. Don't use it and see if you come across problems that this could have addressed. You don't need to be a developer for long to realise how crucial it is to keep different parts of your application as loosely coupled as possible.

Entity Framework 4 website architecture

Hi I've been given the task of creating an N-Teir website using the Entity Framework 4 and am coming up against some brick walls, more than likely in my knowledge.
My plan so far was to have these layers
Website (application layer),
What I'm calling Name.Framework (BLL),
Name.Data (DAL),
Name.Entities (contains POCO classes and other struct classes used in website/bll,
Name.Common (utility class)
I've tried to use the repository class, but am struggling to make things work how I thought they would. Below are a few examples of what I'm getting stuck on.
If I want to use .include() would this be in my Repository or is this the responsibilty of the business layer? (and I have no idea how this would work in the BLL)
Same question for .Order()? As I understood it this would need to be in repository or at least passed into the repo in some way?!?
Should I be using the BLL to pass in the Context to the repository/data layer? At the moment when I get an entity from the Data layer any navigation properties that weren't referenced in the repo just come back with 'Object Context Disposed', should the Business layer still hold the context etc so that this wouldn't happen?
Or to summarize this HELP!!!
I need to have this in some sort of order by tomorrow (eek!) as the project leader wants to know if we are going to continue with Entity Framework or move to NHibernate as in-house we have more knowledge of it.
Thanks for any help or suggestions
Matt
Looking for something similar myself I found this. Not looked into it too much at the moment but looks promising.
I'm currently working on a web hobby project with EF4 Code-Only, where I have the following structure ([name] being the name of my project):
[name].Web - An ASP.NET MVC 2 project
[name].Web.Models - Custom view models, along with AutoMapper mappings from my entity objects
[name].Models - My POCO classes, and interfaces for repositories
[name].DataAccess - Some interfaces related to data access, for example IUnitOfWork
[name].DataAccess.EF - All Entity Framework related classes and interfaces
I also have a test project for each of the above, plus a couple of projects with helpers and extensions for the tests.
It might be relevant to mention that part of the purpose of this hobby project is for me to learn how to use EF4 with some design patterns of my own choice (the ones that concern EF in this project are the Repository Pattern and the Unit of Work pattern). Another partial purpose is to build up a code base that I can re-use in later projects, and this has affected the division between projects in my application - for example, if I wasn't concerned with re-use, I'd probably have all data access related classes in one project instead of two.
I've implemented a basic EF, poco, Repository, UnitOfWork architecture largely following this article here:
http://devtalk.dk/CommentView,guid,b5d9cad2-e155-423b-b66f-7ec287c5cb06.aspx
I found it to be very helpful in these endeavors. Don't know if it helps you but others might be interested in the link.

Asp.net Mvc: Creating Model Classes with LINQ to SQL

I am trying to learn Asp.net Mvc so I am trying out
this Tutorial.
They talk about the Repository Pattern and how it is easy to change to another data access technology instead of just calling Linq to Sql directly.
Using LINQ to SQL within a controller class makes it difficult to switch data access technologies in the future. For example, you might decide to switch from using Microsoft LINQ to SQL to using the Microsoft Entity Framework as your data access technology. In that case, you would need to rewrite every controller that accesses the database within your application.
Note: I never really understood how an interface worked before reading this tutorial and it's still not 100% clear. I see it now as some sort of 'template' for a class.
After successfully using Linq to Sql I thought it would be nice to try out Ado.net Entity Framework since I've been reading a lot about this. They said using the Repository Pattern would make it easy to switch so I thought I would test that.
My question is: what should I do to change to Ado.net EF?
This is what I think I should do.
Add the Movie.edmx file and configure it(add my movie table).
Write a new class based on the IMovieRepository and maybe call it MovieEFRepository.
Change the parameter in the controller constructor to MovieEFRepository. This is the first thing I find strange because in the tutorial they say that not using the repository will force you to change all the controllers if you change to an other datasource. Don't I need to change every controller anyway since I am specifying the MovieRepository class?
The last adjustment I think I need to do is to change the View. Because it's using the Product class which was created by the Linq to Sql designer. I am not sure how I am going to do this. I guess I should have used some object that wasn't dependent on the dbml file?
Forgive me if I have a slightly simplistic view of Asp.net Mvc. I am webdesigner with a lot of interest for Asp.net webdevelopment.
So after a few days of reading and a lot of googling I got it to work. First I tried to find out what IoC (Inversion of Control) actually meant.
One of the first sites I found was a website with a screencast about Unity. Which is a DI/IoC framework for .Net.
Link: David Hayden screencast on Unity.
Looking at it now this is actually a very good screencast and example on how easy it is to use Unity and IoC/DI. At the time I didn't understand it completely so I went on and kept googling.
One website I kept running into was the one from Martin Fowler.
Link: Martin Fowler - IoC Container and the DI pattern
For me, a person that is a coding novice this website is a little to abstract. Also this might sound weird but the font, line-height and typography on that website was really awful which made it even harder to read.
The next website I read was about Windsor Castle since Alfredo Fernández said it was easy to use.
Link: Castle Project- Windsor Container
The documentation wasn't to bad but I had some problems converting their "getting started" basic example to my Asp.net Mvc application. Also part 2 and 3 were missing from their getting started.
After this I started looking for the different frameworks to see if i could find a really basic example. If I just looked at the first screencast again I would have fixed it a lot sooner but somehow I lost track of it.
Link: Scott Hanselman: List of .NET DI Containers(IOC): very good blog post with most of the .NET IOC solutions.
Link: Phil Haack: TTD and DI using Structure Map: Using the xml configuration file was to complicated for me and i couldn't get it to work.
Link:
Andre Loker: ASPNET-MVC-with-Windsor-programmatic-controller-registration: Didn't try this example. Looking at it now I might have been able to get it to work.
Link: MvcContrib: This adds functionality to Asp.net Mvc. It also has 3 or 4 IOC ControllerFactories build in. I couldn't get it to work I also didn't find a lot of documentation about this.
I had a lot of problems with xml configuration files and I couldn't seem to get them to work. I tried Windsor, Structure Map and Spring.net but I always got stuck with the xml files.
So I decided to go to the Asp.net Mvc site because that's where I started learning about Asp.net Mvc. I found the first screencasts and MIX09 presentations very clear and I understood most of what people were talking about. I got stuck at the second screencast by Rob Conery when building the Storefront application. Because I knew a little more about repository and IOC/DI now I thought it would a be a good idea to start watching Rob Conery's screencasts again. In one of the screencasts he talks about uploading all the samples to codeplex.
Link: Codeplex: Mvc sample apps
I went to codeplex and found out you can browse through the source files without downloading them. I tried to find out how Rob Conery handles IOC/DI with his repositories. So I was glad to see he was using Structure Map but instead of using a xml configuration file he was using a bootstrapper class that registers all the interfaces to their concrete class.
After trying this with my webapplication I finaly was able to get Structure Map to work in my application (Hooray).
He also showed me how to fix the dependency on my Product class that comes from Linq to Sql. He creates an extra object that then gets called by "select new product { }" in the Linq queries.
Wow, this answer is a little longer than I planned but I hope this helps other people like me who are very novice in coding and Asp.net Mvc.
You might have your repository decoupled because of injection, not if you followed just the examples because of
public MoviesController() : this(new **MovieRepository**())
I recomend you to read about IOC, is easy and very interesting, you can use and ioc container like castle windsor.
With that, your contoller will have only one constructor, the one with the interface, and not will need to be changed.
With your entities you can do the same that with the controllers, create an interface for each entity and use the ioc pattern too, with tha you will only have to change your configuration file for your ioc container.
If you don't do these things, your right, you will need to change all you said.
I hope that help! sorry about my english!

How should I structure a simple ASP.NET MVC app?

I've been reading a few things about ASP.NET MVC, SOLID and so on, and I am trying to figure out a simple "recipe" for small-to-medium ASP.NET MVC apps that would put these concepts together; the issue that I am most concerned with is ending up with controllers that are too complex and being like code-behind files in webforms, with all type of business logic into them.
I am considering the following architecture, for a small data-driven app:
Controllers: only handle requests, call an appropriate service and return the action result to the View;
Models: POCO, handle all the business logic, authorization etc. Depends on repositories, totally ignorant of persistence infrastructure.
Repositories: implement IRepository<T>, use dependency injection and is where my db code will reside; only receives and returns POCO.
I am considering having services between the controllers and the models, but if they will just pass forward method calls I am not sure how useful it would be.
Finally there should have unit tests covering the model code, and unit+integration tests covering the repository code (following the "red-green" practice, if possible)
Thoughts?
Ian Cooper had a good post on exactly this recently:
The Fat Controller
Simple recipe: (view)Presentation Layer using ASP.NET, (controller)Code Behinds or AJAX Services Layer, (model)Application Services layer, Business Model layer, and Persistance/Data Access layer.
Of course you can slice and dice numerous ways to deal with complexities in order to build a clearly readable and understandable application.
For a recent discourse on the subject, which I have found to be very good, check out this newly published book: Microsoft .NET: Architecting Applications for the Enterprise.
These walkthroughs are quite helpful:
MVC Framework and Application Structure
Walkthrough: Creating a Basic MVC Project with Unit Tests in Visual Studio
Also see: aspnet-mvc-structuring-controllers
Rob Conery has the best answer IMO.
Check out his MVC Storefront Application, which comes with complete source code and video tutorials.

Resources