Sharing a database between two ASP.NET MVC 3 applications on Azure - asp.net-mvc-3

(I had a hard time titling the question so feel free to suggest edits)
Here's the situation: we have just started building a system which is comprised of two integrated MVC 3 web applications running on Azure with a shared AzureSQL database. There are many reasons for running two apps instead of one and I'd rather not get into that...
Originally, database was created code-first from the MVC application "A". 75% of entities from all created will be relevant to application "B" plus application "B" will need a few entities specific to it.
Currently, the entities-defining classes have been extracted into a class library so within the application "A" solution to allow for reuse in application "B". But I am still unsure how to go about adding entities required for application "B"...
The question is: what is the best way to manage the database development/management in this situation? Specifically, where should the definition of entities be? Should we just have a separate db project defining the database and work db-first? (with this option being my preferred at this stage).
Since both of the devs (me and the other dev) working on this are new to MVC and EF, any advice would be much appreciated.

Without seeing what you have its not entirely mapping here in my brain - but I think I may have an idea on this.
Can you create an additional projects containing your models (data access layer) that has your entity framework edmx (or code first) and poco templates installed. This project will be shared by both applications - ie both projects get this assembly and both have the ef connect string in their web.configs.
Another approach is to put all code first into a single project (whatever.domain, whatever.models) etc. Your mapping code then goes into your DataAccess project
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove();
modelBuilder.Configurations.Add(new CustomerMap());
...
}
You now have shared poco classes and a single data access layer.
Some treat their poco classes as their domain objects (theres no problem with this) and their business logic goes in the poco classes. This is fine as long as your poco objects themselves remain persistent ignorant and ideally you don't want to reference implementation specific components in your poco classes. For a good writeup here see:
POCO - if POCO means pure .net class with only properties, where i can write validations in MVC
Personally I like db first and then reverse engineer it using the EF power tools to have a code first model as if you ever want to integration test it, you can simply create the db for your integration tests and remove it when done.

Related

How to create a repository (using EF) so that I can remove the EF reference/DLL from my MVC project?

I would like to create a DataAccess / DataLayer project and encapsulate EF there, so that my MVC project doesn't know that I'm actually using EF. I may decide to use NHibernate in the future, and the out-of-the-box MVC project created by Visual Studio adds EF referece/DLL to the web project.
I cannot access the DbContext from MVC of course, because it needs EF reference.
As a result I wouldn't be able to use Code First data annotations, due to EF being required.
Is it worth creating a repository, or should I keep it "simple" and add EF reference to my MVC project?
It just doesn't make sense to me that I need to add a reference to EF to all my projects, tests and clients that use the context/database.
Thanks
What you are trying to create is the typical layer pattern. At the top you have the Presentation Layer, in the middle you have your Business Layer, and at the bottom (or last layer), you have your DAL layer.
How you design your layers is completely up to opinion and need, but the way I described it above requires you to have 3 different projects. A MVC project, a Logic project, and a DAL project. The DAL project will contain your EF reference and your repository objects. It's then up to you to convert your DbContext/ObjectContext items to POCOs to use them in the business layer. The business layer would know about EF (depending on how you pass your EF objects around), but the business layer would then pass it's own objects (mapping them from your DAL layer objects) to MVC -- thus completely decoupling EF from the MVC layer.
If you are going to use this type of pattern, you should go a step further and include Dependency Injection with a bootstrapped container (crosscutting project using Unity Framework, or something like that).
See Microsoft Pattern & Practices, http://msdn.microsoft.com/en-us/library/ff650706 (Chapter 25 is a good example of layering).
HTH
I choose to implement the repository system in just about all my projects for the exact purpose of decoupling my DAL from any one DataAccess technology or even a specific database.

Entity Framework POCO Serialization

I will start to code a new Web application soon. The application will be built using ASP.Net MVC 3 and Entity Framework 4.1 (Database First approach). Instead of using the default EntityObject classes, I will create POCO classes using the ADO.NET POCO Entity Generator.
When I create POCOs using this tool, it automatically adds the Virtual keyword to all properties for change tracking and navigation properties for lazy loading.
I have however read and seen from demonstrations, that Julie Lerman (EF Guru!) seems to turn off lazy loading and also modifies her POCO template so that the Virtual keyword is removed from her POCO classes. Julie states the reason why she does this is because she is writing applications for WCF services and using the Virtual keyword with this causes a Serialization issue. She says, as an object is getting serialized, the serializer is touching the navigation properties which then triggers lazy loading, and before you know it you are pulling the whole database across the wire.
I think Julie was perhaps exagarating when she said this could pull the whole database across the wire, however, even so, this thought scares me!
My question is (finally), should I also remove the Virtual keyword from my POCO classes for my MVC application and use DectectChanges for my change tracking and Eager Loading to request navigation properties.
Your help with this would be greatly appreciated.
Thanks as ever.
Serialization can indeed trigger lazy loading because the getter of the navigation property doesn't have a way to detect if the caller is the serializer or user code.
This is not the only issue: whether you have virtual navigation properties or all properties as virtual EF will create a proxy type at runtime for your entities, therefore entity instances the serializer will have to deal with at runtime will typically be of a type different from the one you defined.
Julie's recommendations are the simplest and most reasonable way to deal with the issues, but if you still want to work with the capabilities of proxies most of the time and only sometimes serialize them with WCF, there are other workarounds available:
You can use a DataContractResolver to map the proxy types to be serialized as the original types
You can also turn off lazy loading only when you are about to serialize a graph
More details are contained in this blog post: http://blogs.msdn.com/b/adonet/archive/2010/01/05/poco-proxies-part-2-serializing-poco-proxies.aspx
Besides this, my recommendation would be that you use the DbContext template and not the POCO template. DbContext is the new API we released as part of EF 4.1 with the goal of providing greater productivity. It has several advantages like the fact that it will automatically perform DetectChanges so that you won't need in general to care about calling the method yourself. Also the POCO entities we generate for DbContext are simpler than the ones that we generate with the POCO templates. You should be able to find lots of MVC exampels using DbContext.
Well it depends on your need, if you are going to serialize your POCO classes than yes you should remove them (For example: when using WCF services or basically anything that will serialize your entire object). But if you are just building a web app that needs to access your classes than I would leave them in your classes as you control the objects that you will access in your classes through your code.

How to architect MVC 3, EF, ViewModels, AutoMapper, POCO, Repository and Unit of Work in n-tiered project?

I have been reading countless articles about how to architect a new MVC 3 application using best practices.
90% of the articles combine the EF EDMX files into the same project as the MVC app. Those that do seperate these items into their own projects don't clarify which project each goes into and what references each project has. Usually they consist of code snippets that are great to teach how to do a specific function, but don't tell me how to architect the solution.
I believe that I need at least 5 projects in my solution. Can anyone tell me if I have the correct layout here?
Data Access Layer - Contains the EF EDMX files. (Perhaps the DBContext auto-generated code?)
Business Layer - Contains the IRepository and Repository classes, UoW classes, as well as the business logic for the domain. - Contains reference to DAL.
ViewModels - Contains the viewmodels that will use AutoMapper to go between my DAL and the presentation layer. - Contains reference to DAL.
MVC 3 App - Standard MVC 3 app. Contains references to the BusinessLayer and the ViewModels projects.
Test - Unit testing.
Does this look right? Can anyone point me to a good article that uses n-tiered development with ViewModels, AutoMapper, Repository patterns and EF4?
When looking at what project to put something in, it helps to think about how you are going to be deploying your code. Put code that will ship together in the same project and then use namespaces to separate it out logically into separate tiers. For most of the projects I work on it tends to be pretty simple with 3 projects.
Business Layer
Domain/Business Model and Services
Data Access Layer
MVC App
View Models
Automapper
Controllers
Views
Tests
Unit tests
I like the following
Domain - contains models and ViewModels
Services -business logic and viewmodel hydrating (ie population) code
Contracts or interfaces - repository interfaces, unit of work, IContext, and ICache
Web site
DataAccess - concrete implementation of entity framework
Some include their AutoMap code directly as an action filter as an attribute inside the web project. My automap code is done in the services project (but again this is up to you) unless I can use the attribute to do it in the controller.
btw see Jimmy's nice attribute here:
http://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/
What you have outlined above is fine as well though. This is a very subjective matter. My general recommendations are that 'if someone can open a project and have an idea where to look for something, you are likely doing it correctly'
The way I usually do it:
Model project - Contains the model generated from the db and the context.
POCOs project - Contains the Business entities
Controller project - similar to your repository
MVC3 project - front end, INCLUDING view models and repository classes that include automapper equivalencies.
Unit tests
Architecture is technology independant, whether you are using EF, Hibernate, MVC, webforms etc... And you usually combine patterns. Besides is mostly depends on each particular project.
Regarding to best practices, when talking about EF, I can't link you to the source I use because I use a book. However I'll link you to the author's blog, it's Julie Lerman's Programming Entity Framework.

How to implement PetaPoco with existing C# 3-tier win app

can anyone help me with converting my project to use PetaPoco?
here is my issue. backend is SQL 2010 database .NET fraimework 4.0
I have an existing 3-tier win app in C# that uses a custom DAL -- each Data call uses stored procs with parameters and either returns dataset or specific value as needed -- each call accepts dataset referenced parameter and baseClass parameter (base class is identical to DB table schema well mostly)
I want to replace my custom DAL with PetaPoco but keep the 3-tier layout
the app is relying on predefined base classes as DTO to pass info between UI-BAL-DAL
does anyone have a sample/example of app solution layout as to how to use PetaPoco in 3-tier enviroment code example would be very helpfull
thanks in advance...
Vlad
Example not really needed
All you have to do is get acquainted with PetaPoco library. The best way is its documentation. It's not a complicated/complex library, so you should get up to speed with it quite quickly.
If you also have you application broken down into projects for each layer (UI, BL, DAL), then the easiest thing to do is to create a new DAL project and implement all used functionality of existing DAL but use PetaPoco in this one. Then just change your project references and voila. That's it. You can keep your POCOs/DAO. If you've used IoC then it will be even easier because instantiating DAL repositories (or whatever you're using) is probably done via some DI container.
Layering and PetaPoco
PetaPoco has nothing to do with application layering. If you use it in 3-tier applicatin that's fine.
What are you using now?
You didn't mention which DAL library (if any) you're using right now. If you don't, then using PetaPoco will result in less lines of code and much simplified object mapping.

advice on architecting asp.net mvc applications

I've been using ASP.net MVC for about two years now and I'm still learning the best way to structure an application.
I wanted to throw out these ideas that I've gathered and see if they are "acceptable" ways in the community to design MVC applications.
Here is my basic layout:
DataAccess Project - Contains all repository classes, LINQ-to-SQL data contexts, Filters, and custom business objects for non-MS SQL db repositories (that LINQ-to-SQL doesn't create). The repositories typically only have basic CRUD for the object they're managing.
Service Project - Contains service classes that perform business logic. They take orders from the Controllers and tell the repositories what to do.
UI Project - Contains view models and some wrappers around things like the ConfigurationManager (for unit testing).
Main MVC Project - Contains controllers and views, along with javascript and css.
Does this seem like a good way to structure ASP.NET MVC 2 applications? Any other ideas or suggestions?
Are view models used for all output to views and input from views?
I'm leaning down the path of making view models for each business object that needs to display data in the view and making them basic classes with a bunch of properties that are all strings. This makes dealing with the views pretty easy. The service layer then needs to manage mapping properties from the view model to the business object. This is a source of some of my confusion because most of the examples I've seen on MVC/MVC2 do not use a view model unless you need something like a combo box.
If you use MVC 2's new model validation, would you then validate the viewmodel object and not have to worry about putting the validation attributes on the business objects?
How do you unit test this type of validation or should I not unit test that validation messages are returned?
Thanks!
Interesting.
One thing I do differently is that I split off my DataAccess project from my Domain project. The domain project still contains all the interfaces for my repositories but my DataAccess project contains all the concrete implementations of them.
You don't want stuff like DataContext leaking into your domain project. Following the onion architecture your domain shouldn't have any dependencies on external infrastructure... I would consider DataAccess to have that because it's directly tied to a database.
Splitting them off means that my domain doesn't have a dependency on any ORM or database, so I can swap them out easily if need be.
Cheers,
Charles
Ps. What does your project dependency look like? I've been wondering where to put my ViewModels. Maybe a separate UI project is a good idea, but I'm not entirely sure how that would work. How do they flow through the different project tiers of your application?

Resources