Repository Pattern in Mvc 4.0 - c#

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;
}
}

Related

scaffolding template for creating repositories

I'm a new comer to the Scaffold world to build repositories creating the CRUD operations.
There are a lot of scaffolding templates ,I'm so confused which one will suit my requirement .
I use asp.net web forms (not asp.net MVC)
I use Entity Framework 6 as ORM .
I want some help to clarify the main pillars we select one scaffolding template over one and what's the proper one for my case ?
NOTE : Right now i use T4Scaffolding .
I think you can use T4Scaffolding, as you already do. But why are you using a "scaffold"? I created my crud app with entity framework without scaffolding anything.
Anyway, the scaffolding tools are all very similar, so T4Scaffolding is perfect, IMHO.
I think you can find interesting this and this.
Let me know if you have other questions.
It looks like you are trying to generate repositories for each model class. If that's the case, my advice will be don't. Moreover, don't be tempted by Generic Repositories (anti-pattern) as well.
For Scaffolding
If you must use scaffolding for generating repositories around your model classes, you may refer to this link for scaffolding repositories using T4Scaffolding.
Note:
If you're using Visual Studio 2013/2015, you would have to use the T4Scaffolding.VS2015 nuget package instead of the older T4Scaffolding package (for older versions of VS).
Aggregate Roots
Firstly, repositories are created on aggregate roots and not per class.
Secondly, although debatable, but EF already implements these patterns.
You many want to read more on repositories; refer t the Matrin Fowler's excellent post.
Why Use Repositories anyway?
Also, there are a bunch of people against it as well importantly for good reasons.
See Rob Conery's post on it. Although, I would prefer using the below solution instead of the one recommended in the post.
The alternate?
BTW, you should consider using commands or tasks instead of respositories. Something like Ayende's post. Of course, you should evaluate your case and come up with your reasons to adopt it. It's just a suggestion, probably a good one ;)

ASP.NET MVC 5 application - Repository pattern without Entity Framework

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.

Repository pattern implementation with ninject

In my project, I trying to implement repository pattern and unit of work.
I found some web site to describe how to implement it such as:
http://www.codeproject.com/Articles/688929/Repository-Pattern-and-Unit-of
http://www.codeproject.com/Articles/561584/Repository-Pattern-with-Entity-Framework-using
I was wondering, why is not generic Unit of Work and Repositories Framework? then try several search on internet and I found it,
http://genericunitofworkandrepositories.codeplex.com/
This framework is first code but my project is model first therefore is not work correctly?
Could you please suggest me model first framework like this?
My project is a internet web site with one database, If there is plausible reason I can change model first approach to code first approach.
Thanks for you time.
We've abstracted all the interfaces in our latest release into Repository.Pattern project https://genericunitofworkandrepositories.codeplex.com/SourceControl/latest#main/Source/Repository.Pattern, in plans to implement nHibernate provider. You are more than welcome to start implementing these interfaces, based on bandwidth at the moment, I cannot commit to any dates as of yet.

"Modules" in Repository Pattern

We're using a Repository Pattern in our latest project. But we have find some difficulties implementing a "module" to that architeture.
In the below image, you can see how the main solution is tiered and how the "module" is tiered.
What we wanted to do is having the module without the responsability of the data access/handling.
That's why we dont have the Repository Pattern there.
Oh, and we are using NHibernate so we are expecting that saving our module in the main bussiness tier will respect the chain of relationship defined in the Modelo Tier in the "module".
Have a look at the following page http://blog.bobcravens.com/2010/06/the-repository-pattern-with-linq-to-fluent-nhibernate-and-mysql/
The author gives a brief explanation about the repository pattern and how he used it on Nhibernate with linq, but you could also use HQL ...
If you search for "repository pattern nhibernate" you'll find a wealth of articles demonstrating the technique.
However, I think it's important to ask as to whether you need to abstract NHibernate any further. In essence, NHibernate can be your repository.
http://ayende.com/blog/4784/architecting-in-the-pit-of-doom-the-evils-of-the-repository-abstraction-layer

How Should viewmodels communicate with repositories?

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.

Categories