I am trying my hands on creating an ASP.NET MVC 5 app without entity framework.
I have some existing database, but do not want to use Entity Framework for that. Came up with simple and uncluttered architecture having Entities, Repository and DAL.
I have created a controller passing Repository context to it.
public class EmployeeController : Controller
{
private readonly IEmployeeRespository repository;
public EmployeeController(IEmployeeRespository _repository)
{
repository = _repository;
}
// GET: Employee
public ActionResult Index()
{
IEnumerable<Employee> Employees = repository.GetEmployees();
return View(Employees);
}
}
Issue here is, I have not created a parameterless contructor for this controller. Now how do I pass my repository context to this controller. I am missing out some step, but not able to figure out.
Also, if anyone know of any downloadable sample application for such scenario, it will be of great help.
Dependency injection is your answer. there are some libraries that will do it for you. You can also do poor-mans injection yourself, or with a service locator.
You can use autofac or ninject that will orchestrate your dependency resolution.
This would help: How do I properly register AutoFac in a basic MVC5.1 website?
I looked at using a Repository design pattern to use with an MVC 5 Application I have been working on, but unfortunately it looked like a major rework of my MVC application, basically I would have to start from scratch again with this application. I found it would be far easier to maintain the MVC application by leaving Entity Framework models intact, even though that slows down the MVC application, my resolution is to have the MVC application run in a virtualized server with more computing resources added to speed up the application. more resources from its current level.
Entity Framework Models are far easier to maintain than using a Repository design pattern, if the application is slow because the EF models have many sub-models as virtual properties, that is ok, the easy solution to the problem is to have a more powerful server running the application, more RAM, faster CPU's, more computing resources, etc.
From my point of view, using a Repository adds far more layers of complexity to an application and makes it more difficult to maintain.
Related
I am having a project which is in Mvc 4.0. The project has already included EF in it nad using its classes with database first Approach. I have to do some work in it using repository pattern. I have read many blogs and I am still confused with how to actually integrate the Entity Framework with Repository. From where I have to start. I am reading this example
The explanation is okay but how can I merge the both concepts.What I tried is created a model class as the above link has suggested but in the above link in student class they have taken list of Icollection where enrollment is table in database . I am also passing my table name to list but not working.
Total Process I have done. Please tell me if this right or Wrong
Step1: I created a database named School
Step2 : I added entity framework in the Project.
Step3: I am now creating a model of the same properties as the Student table has.
Step4 : where I am now stucked. How will I create a Icollection??
Please help as soon as it can be possible. I will be thank ful to you.
Check out this question Unit Of Work & Generic Repository with Entity Framework 5 I think it is described well there.
Here is complete package you can use http://www.nuget.org/packages/Repository.EntityFramework/
And one more link: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application.
BUT before implementing repository pattern I would suggest you to think "Do you really need it?".
If you would like to see a real world scenario of how the Repository is implemented then I suggest you check out some open source projects.
Nop Commerce
Uses the repository pattern and dependency injection
http://nopcommerce.codeplex.com/
Videos
There is also the ASP.NET video series (free) about building an MVC Storefront
http://www.asp.net/mvc/videos/mvc-1/aspnet-mvc-storefront/aspnet-mvc-storefront-part-2-the-repository-pattern
Open Access samples
Telerik has some great examples using their ORM (OpenAccess). Even though it uses a different ORM, the repository pattern is still applicable to EntityFramework.
http://www.telerik.com/products/orm.aspx
Here is an example that you might find useful: Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application, from www.asp.net
Here is some article which explain basic about Repository Pattern also sample example with source code.
CRUD Operations Using the Repository Pattern in MVC
Repository pattern, done right
Generic Repository Pattern in MVC3 Application with Entity Framework
public class AccountBrandRepository : GenericRepository<AccountBrand>
{
TestEntities _context;
public TestRepository(IUnitOfWork unitOfWork)
: base(unitOfWork as VoltEntities)
{
if (unitOfWork == null)
throw new ArgumentNullException("unitOfWork");
_context = unitOfWork as TestEntities;
}
}
I am currently working on a solution in visual studio which I am going to deploy on windows azure. The solution consists of a MVC3 web role where data from SQL Server is represented.
I've already set up Ninject and Fluent NHibernate to decouple the views from the database and the concrete implementations.
What I'd like to do now, is to put all the data access logic (i.e. NHibernate along with the repositories for data access) into a separate c# project so that I can reuse this project for the MVC3 project AND a future SOA project.
Any ideas how I may achieve this? I figured out how to do it with "code-only" classes, but a handful issues come up when using hibernate. I guess it's related to the ISession object in the global.asx which is created for each web request.
Any hints to simple implementations, scenarios or how-to's would be very helpful. If needed I can post code as well - just let me know which parts in detail ;-)
Regards,
Martin
If I understand correctly, I don't see a problem implementing a Service class library that gets requests from either the UI or the SOA layer and executes them. for example-
public class UsersService
{
private ISession _Session;
// Session is injected
public UsersService(ISession session)
{
_Session = session;
}
public IEnumerable<User> GetAllUsers()
{
return _Session.QueryOver<User>().List();
}
}
I am trying to get my hands on MVC. I am from ASP.Net background.
After creating new mvc 3 application, i got Controller, Models and views under the same webapp project. In ASP.Net, we generally create separate projects for Models and Controllers (which i assume are same as Business Layer). Also i created a separate project for DAL where i will be using EF.
I am confused as is this the ideal solution structure? Should we not create separate projects for each layer? Since i created DAL as a separate project, i had to put a reference of WebApp in it because i wanted to return Model from the DAL and because of that now i am not able to add a reference of DAL to my WebApp.
Can someone please throw some light on what am i missing here? Am i not doing it right?
MVC really leaves the "M" part up to the developer.
Even in their official examples you'll see variations. Your question exposes one of the most common misconceptions about MVC. You should NOT bind your domain or data models directly to views, nor should your controller methods accept them as parameters. See this post on over and under-posting.
Ideally, your controllers will call out to a DAL, and some mechanism will map those Data or Domain models to View models. It is those View models - models that exist specifically to facilitate the UI - that should exist in the WebApp "Models" folder.
So, you were definitely on the right track creating a new assembly to contain your DAL. One of the "easiest" mechanisms for mapping to a ViewModel is a simple method on each ViewModel:
public class MyWidgetFormModel()
{
public string Name { get; set; }
public string Price { get; set; }
public MapFromDAL(DAL.Widget widget)
{
this.Name = widget.Name;
this.Price = widget.Price;
}
}
Update: based on your comments, here is an excellent answer about one user's project layout.
When I started with MVC i followed the Jeffrey Palermo onion architecture. You can read about it :
here : http://jeffreypalermo.com/blog/the-onion-architecture-part-1/
here : http://jeffreypalermo.com/blog/the-onion-architecture-part-2/
and here : http://jeffreypalermo.com/blog/the-onion-architecture-part-3/
It's using a IoC support for decoupling services. I think that you should consider usage of IoC containers because the MVC architecture was thought around patterns using IoC in order to decouple services (layers).
You can also dowload a working sample from http://codecampserver.codeplex.com/ using onion architecture.
It's not the only architecture you can use with MVC but it's a very good place to start and to learn about IoC and decoupling in MVC applications.
I got a bunch of repositoiries. They retrive data from a EF 3.5 generated model. For the sake of simplicity let's just call them repository1,2 and 3. They all implement the generic interface: public interface IRepository<T>{..} How should my viewmodels communicate with theese repositories? I tried to create some kind of a factory with a IRepository GetRepository(string repositoryName){..}method, but I couldn't get it to work. So should I just reference the repositories in the viewmodels when needed or is there a better solution to this? I would prefer a code sample, thanks.
cheers
These answers and the free introduction-chapter from Dependency Injection in .NET recommend having the repositories and ui separated from the businesslogic. Dependencies should go towareds the core-logic like this:
dal/repositories -> Businesslayer, Models and IRepository <- UI
I have also wondered where the ViewModels fit into this. They should definetly not be connected to the repositories at all, but whether the ViewModels belong in the businesslayer (servicelayer) or with the UI seems debatable. I'm just staring out with asp.net mvc and are currently most if favour of putting them with the businesslayer to keep the controllers simple. Also it seems reasonable that the businesslayer gathers items from various repositories that logically belong together and that they are acted on together via the ViewModel. Maybe as a transaction, so that updates to all repositories must succeed or be rolled back.
I can't think of a situation where your view model should EVER communicate with your repository. A ViewModel should be a flat model for use by the Client.
What exactly are you trying to do?
You might find the BookLibrary sample application of the WPF Application Framework (WAF) interesting. It uses the Entity Framework together with MVVM. But it doesn't introduce a repository to work with the Entity Framework.
A Repository serves up T's. What I've done is add a static property to my T's to get the repostory via IOC:
public class Part // This is one kind of T
{
public static IRepository<Part> Repository { get { return IoC.GetInstance<IRepository<Part>>(); } }
...
}
then when I need a Part...
var part = Part.Repository.Find(id);
For my unit testing IoC serves up mock repositories. In production, the real thing.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to learn MVC with ASP.Net and am reading Steve Sanderson's book. One thing I'm confused about is where to place the business logic?
For example, when deleting a product all Sanderson has is a method in his CartController that calls the Delete method on the productsRepository. This is strange to me because if there were any business logic, such as ensuring that the product isn't in anyone's shopping cart first, etc. it would have to either be in the products repository or the CartController.
Both of these seem like bad places to put business logic; the products repository is meant to be easily replaced with another (switching from using a db to using a session) and using the Controller means you are putting the business logic in the UI layer.
Shouldn't he be using a class that contains the business logic and calls the repository's delete method instead? The repository being a member variable of the business logic class'?
I typically structure my MVC solutions in a way resembling the following:
X.Core
general extension methods, logging, and other non-web infrastructure code
X.Domain
domain entities and repositories
X.Domain.Services
domain services for orchestrating complex domain operations, such as adding a product to a shopping cart
X.Application.Core
application logic (initialization (route registration, IoC configuration, etc.), web-specific extensions, MVC filters, controller base classes, view engines, etc.)
X.Application.Models
view model classes
X.Application.Services
service classes that can return ViewModels by accessing repositories or domain services, as well as the other way around for updates
X.Application.Web
controllers, views and static resources
Some of these could be combined, but having them separate makes it easier to locate stuff and to ensure your layer boundaries are respected.
A typical controller action for showing the product cart might look like this:
public virtual ActionResult ProductCart()
{
var applicationService = <obtain or create appropriate service instance>
var userID = <obtain user ID or similar from session state>
var viewModel = applicationService.GetProductCartModel( userID );
return View( "Cart", viewModel );
}
A typical controller action for adding a product to the shopping cart might thus look something like this:
public virtual ActionResult AddProductToCart( int productID )
{
var domainService = <obtain or create appropriate service instance>
var userID = <obtain user ID or similar from session state>
var response = domainService.AddProductToCart( userID, productID );
return Json( new { Success = response.Success, Message = response.Message } );
}
I also read Sanderson's first version of his book and it was fantastic - a very easy way to pick up and start using ASP.NET MVC. Unfortunately, you can't jump straight from the concepts in his book to writing a large maintainable application. One of the biggest hurdles is figuring out where to put your business logic and other concerns that lie between the UI and persistent storage (a concept called Separation of Concerns or SOC).
If you are interested, consider reading up on Domain Driven Design. I won't suggest that I know it perfectly, but serves as a good transition from Sanderson's sample applications into something that successfully separates UI concerns, business logic, and storage concerns.
My solution has a separate service layer. The controllers communicate with the service layer (using Dependency Injection - Ninject). The service layer has access to my domain objects / business logic and my repositories (NHibernate - also spun up with Ninject). I have very little logic in my views or controllers - the controllers serve a purpose of coordinator and I strive to keep my controller actions as thin as possible.
My domain layer (entities, business logic, etc.) has no dependencies. It does not have references to my Web project or to my Repository project. It is what is often referred to as POCO or Plain Old C#/CLR Objects.
EDIT: I noticed in one of your comments you are using EF. EF does not support POCO without using something called Code First (was in Community Technology Preview status when I checked last August). Just FYI.
The reality is that there's no silver bullet to this answer, and it really is a contextual question at heart. I like to separate things as much as possible, and business logic is, if you think about it, just another layer in an app.
I worked up a BDD-inspired decisioning engine and released it as an OSS project available via NuGet. The project is called NDecision, and you can read about it on the NDecision project home page.
NDecision makes decision-tree business logic quite simple to implement, and if you're a fan of Gherkin syntax and Fluent coding practices you'll feel right at home using it. The code snapshot below is from the project site, and demonstrates how business logic could be implemented.
This might not be a solution for you, but the idea is, if you already have your domain model in one assembly - a great idea and common practice as suggested in another answer earlier, there's no reason why you can't have another assembly with your "decision tree." NDecision was written with that in mind, to separate the logic into one independent layer.
Hopefully that'll be of some assistance.
If you want scalability, it's bad practice to use data access objects directly from the GUI. So in the example you mentioned, I think you should replace the repository that directly reads or writes to the DB by some business logic class that supports business operations.
I'm trying to learn MVC with ASP.Net
and am reading Steve Sanderson's book.
One thing I'm confused about is where
to place the business logic?
In the model (M in MVC), or domain layer. These are a separate set of types (preferably in a separate project) that represent domain models, services and repositories.