.NET MVC3 Project Structure - asp.net-mvc

I have looked around but cannot find anything that answered this particular question related to file/project structure.
I have an MVC3 site using entity framework. It follows a basic generic repository pattern using StructureMap to handle dependency resolution.
My question is, how do I lay the projects out? taking in mind I may want to expose the database to another application down the track.
Currently I have:
mySite.Web -- MVC Project also has all the dependency resolution
mySite.Web.Data -- EntityFramwork CodeFirst, Repository pattern
mySite.Web.Tests -- Tests... :-)
Should I be moving my EntityFramwork models to there own project? if so where would things like my EntityContextFactory go?
Thanks

I have the same problem - How to setup a new mvc project?
My research and help for other user is: A good structure approach is the Domain Driven Design for MVC Architectures.
good blog post for DDD
my new project structure will look something like this:
Presentation.Web (Controller, Views, ModelViews..)
Presentation.Web.Utils (Helper and Extensions..)
Presentation.Web.Tests (Moq..)
BusinessDomain.Services (Business Service for DI )
BusinessDomain.Models (EF Models..)
BusinessDomain.Tests (Moq..)
CrossCutting.Common (Const, Resources, Exception Msg...)
Infrastructure.Configuration (IoC Bootstrapper, ApplicationConfiguration,ContainerExtensions..)
Infrastructure.DataSource (DbContext, Repositorys..)
Infrastructure.Tests (Moq..)

I would create a new project called mySite.Domain and possibly create a entities folder in that project and place them in there.
I'd only store entities in the Domain and keep all repositories, your dbcontext and entity contextfactory in your Data project.
Here are some sample projects you could have a look at (credit to authors):
http://myfinance.codeplex.com/
https://github.com/darind/samplemvc
This is largely subjective though.

No this structure is good.you may move pattern repository to mySite.Web or create another class library project for it but it is not necessary.

Related

Entity Framework References, Multi Layer App

I have set up my MVC app with seperate Class Libraries for my Domain (POCOs) and Repositories. Now my DbConxet is currently in the domain layer and i wanted to add the following:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
but it couldnt find DbModelBuilder. Now I checked my references and noticed it was referencing EFCodeFirst0.8/lib/EntityFramework.dll When I changed this to EntityFramework4.2.0.0/lib/EntityFramework.dll DbModelBuilder was available but I get errors because the other projects in my solution (MVC and Repo) are referencing the original dll. So I update them but then the MVC layer has a problem in App_Start/SQLCEEntityFramework.cs
What have I done wrong?! Should I have the OnModelCreating in another part of my app and reset all the references to the original EFCodeFirst0.8/lib/EntityFramework.dll? Or fix up the errors in App_Start/SQLCEEntityFramework.cs?
Thanks all,
James
You are doing it wrong :)
There is really no point in POCO, repository pattern, and all that stuff intended for persistance ignorance, when you have entity framework referenced everywhere and your domain is tied with it.
Your domain should be pure class library (with things like componentmodel, dataannotations of course) without referencing EF.
Then you should have "contract" (that is interface, in another class library) between your MVC app and "all the possible repositories" - also EF agnostic.
And finally you have "one particular implementation" of that contract - your EF repository. That should be the only project referencing EF library.
The point is, that if tommorow your boss comes and says "ok, we switching to nhibernate", you sould replay "no problem, i just write another repository implementing this interface with it and change 1 line in IoC container configuration". And as a bonus, you can update your EF reference in 1 place only :)

MvcScaffolding - Does it support Model-First?

I've toyed around with the MvcScaffolding project - very nice BTW; however, does anyone know if it supports Model First design scenarios (e.g. EF4 Data Model -> Generate from Database)?
If it does in-fact support Model First scenarios, do you know of any links describing a Model First design scenario?
Thanks...
MvcScaffolding is pretty flexible in terms of what scenarios it's scaffolding will work for. However to support anything other than the default which is code first you may have to tweak the output a little. MvcScaffolding itself doesn't have any constraints around rather you're using model first, code first or whatever. All you have to do is point it to a public class and it will scaffold it.
However, the text templates that ship with MvcScaffolding are designed to generate controller code that interfaces with EF 4.1 code first types, so there would be some tweaking of the generated controller code necessary to support a model first scenario.
I just completed an entire MvcScaffolding implementation using a model first approach. In my case I didn't want to use entity framework 4.1 which is still pre-release. Additionally, I didn't want to hand code all of the types required by my entity model. Rather than tweak the output after the generation was complete, I edited the templates to generate the code exactly the way I wanted it. The end result was I was able to generate, compile and run against a model first entity framework 4.0 implementation.
MvcScaffolding isn't picky about what scenarios it will scaffold code for if you're not afraid to tweak it a little. It is definitely easier to work with code first scenarios as implemented in entity framework 4.1 but with a little work you can get it to support model first scenarios as well.
I'm exploring this too currently. Here is an example using Northwind
http://weblogs.asp.net/scottgu/archive/2010/08/03/using-ef-code-first-with-an-existing-database.aspx
Also looks like there is a gotcha
http://mvcscaffolding.codeplex.com/discussions/247163
Some of my notes and screenshots here:
http://www.programgood.net/2011/03/11/EntityFramework.aspx
Check out LinqConnect at http://www.devart.com/linqconnect/. I haven't used it yet, but I've been researching it over the past week and I think it sounds exciting.
Building an MVC 3 App with Model First and Entity Framework 4.1
Julie Lerman show us how to do it by hand on MSDN
My suggestion: after strongly typed entity classes have been generated under Models folder and real database has been created, use mvcscaffolding:
PM>scaffold Controller MyEntityClass
Yes it does. And very well too.
i.e. I am using it successfully with the new DbContext POCO T4 templates
e.g.
Add your edmx => update from database
Right click the edmx designer
Select "add code generation item"
Select ADO.NET DbContext Generator
This will remove the : ObjectContext derived .designer.cs code, and replace with the DbContext .tt files.
Then scaffold away ! (remembering to pass the -DbContextType into your scaffolding cmds)
I have come up with the steps to do this for a database first scenario. See http://weblogs.asp.net/paullitwin/archive/2011/08/11/use-mvc-scaffolding-in-database-first-mode.aspx

Where to put Entity Framework Data Model in MVC application?

Lets consider default ASP.NET MVC application folder structure, so it's looks like this:
-App_data
-Content
-Controllers
HomeController.cs
-Models
AccountModels.cs
-Scripts
-Views
My question is: Where is the best place to put Entity Framework Data Model (EDMX) file? Is it Models folder? Yes - we know that good solution is to introduce new Project and reference it to MVC application, but lets forget about this now.
For a small project, it should be part of the Model. For a larger product, the repository and the associated model could be in a separate assembly.
Well this is debatable, but i'd vote +1 for the Models folder.
The only other candidate would be App_Data, but this is generally for file-based databases (SQL Server CE .MDF, for example) and files you don't want served by IIS.
As the EDMX is an abstraction of the database, it should go into the Models folder.
If the project gets bigger, you should definetely move your EF Model into another project. To future-proof yourself from this, make your Controllers access the EDMX via Repository/Interfaces, so when you move the DAL over to another project, all you'll have to do is add the reference and add in the using statements.
I would put the EF-model (aka physical model) always in its own assembly or in a "core" assembly outside of main MVC application. The same applies for your business-logic / domain-logic / domain-services / etc. Separate the non-web stuff from the MVC-Web-Application.
This will help you re-use the core part of your app. For example when you need to expose it as a service, a command-line tool, migration-tool, etc.
Because storing this in its own assembly is so easy and takes you a few minutes I highly recommend doing this for each and every tiny app too.
My opinion is that you should create
a separate project for domain objects, datacontracts etc. etc...
Like MyProject.Infrastructure including many folders like
DataContracts, Model, Exceptions etc.
a separate project for DataAccess wich contains the DBContexts and the Repositories, this way you can easily manage migrations later on

MVC 2 and Entity Framework - Should I put Entity classed in separate layer?

I'm trying to find some information on preferred solution setup when using MVC 2 and Entity Framework, and it would seem most intuitive to me to set this web app up in 3 layers:
MyProject.Web (MVC project for presentation)
MyProject.Data (Data gateway layer using Entity Framework to speak to the DB)
MyProject.Tests (Test project as created when setting up a new MVC project)
This seems to be contrary to the examples I'm finding, and the documentation (eg, the NerdDinner example) which see the MVC project as mediating directly with the database. The NerdDinner example puts the data access in a repository class mixed in with the MVC models.
I've tried going with the way which seems best to me, and have created my "ADO.NET Entity Data Model" item in my separate Data project, but this gives me an error when I try to use MVC to list the items in it:
"Unable to load the specified metadata resource."
unless I have a copy of the Entity Data model in my MVC project as well.
Before I go too far down the road of looking into this error, I want to find out if I'm just fighting against the framework for purism when I could just be disciplined with only using data access in my repository.
so:
- Is it even possible or recommended to put my Entity Framework def in this other project?
- Will I be sacrificing certain other MVC features by separating it out in this way? (eg, validation?)
- If I'm heading in the right direction and others agree, are there any other examples or docs out there someone could point me at?
Yes, I think it's a good idea to put your entities in a separate assembly.
One way to fix the "Unable to load the specified metadata resource" error is to specify the assembly in the connection string explicitly:
<connectionStrings>
<add name="MyEntities" connectionString="metadata=res://*/AssemblyName.bin.Namespace.MyEntities.csdl|res://*/AssemblyName.bin.Namespace.MyEntities.ssdl|res://*/AssemblyName.bin.Namespace.MyEntities.msl;provider=System.Data.SqlClient;provider connection string="Data Source=SERVER_NAME;Initial Catalog=DBName;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>
</connectionStrings>
Note, especially, the AssemblyName.bin.Namespace.MyEntities. This is the assembly-qualified resource name (assuming the assembly is called "AssemblyName.dll". You may need to use Reflector to figure it out the first time you do this.
This answer might also be helpful.
It is certainly possible to put your Entity Framework definition in another project. Personally, I keep it in another project if the data layer will need to be shared by multiple interfaces (MVC, WCF, WPF).
Take a look at these two MSDN articles on building and using an EntityConnection.
Build an EntityConnection
Use EntityConnection with an Object Context

ASP.NET MVC - Strongly typed view model, where does it belong?

I'm trying to create a strongly typed view model as John Sheehan suggests here. Where should it go? I can make arguments to myself for Model, View, and Controller.
It should go in the "Models" directory of the web app. ViewModels are by definition specific to one or more views and therefore belong in the web app, not the core.
You could define them in the controller that uses them, but this doesn't scale. Same with defining the class in the view code. Even though one-class-per-file means more files, its easier to find code and easier to maintain.
I'll often create a subfolder for each controller, so I end up with things like Web.Models.Foo.BarViewModel.
If have them in my Domain project in a PresentationModel directory and like #Seth Pretry-Johnson, I have them in separate Controller directories.
This is my overall structure of a project:
Website Project
Controllers
Views
Etc
Domain Project
Models
Repositories
Abstract
Services
Abstract
PresentationModels
Home
User
Etc
DataAccess Project
Repositories
HTHs (and doesn't raise more questions.. ;-),
Charles
I put the actual model class in the Models folder.
/Controllers
/Models
/Entities
/Mappings
/ValueTypes
/ViewModels
Something like that. I'm a big fan of the Fluent NHibernate.
It can go wherever you want it to go, why do you need someone to tell you where to put a class?
A lot of people have the wrong idea that, unless you put your classes inside some specific directory grouped by functionality, things will not work. This might be true with other frameworks, but with ASP.NET MVC it's not true. Code is compiled to assemblies.

Resources