Writing a custom version of DbContext - asp.net-mvc

My company has a product that ultimately exposes a bunch of object types that I want to be able to interact with via a custom DbContext and DbSet classes so that I can perform CRUD activities against them in an MVC based website.
So basically what I want to do is have the equivalent of DbContext (http://msdn.microsoft.com/en-us/library/gg679505(v=vs.103)) and DbSet such that they are not tied into a database in the background, but point at our server product instead.
But I have no real idea on how to do this. Is this even possible or would it be some kind of nightmare to achieve. I've searched around but have not had much luck finding anything of this nature, which probably indicates that it is a nightmare.
Any pointers in the right direction is much appreciated.
Thanks

See if this helps: Write a custom DbContext

Related

ASP.NET MVC - DbContext good practices

I'm starting a new .NET MVC project with Entity Framework and I am struggling with some problems.
In my model I have about 150 entities (generated from the database). Is it a good idea to have only one DbContext? If not, how should I divide my entities?
If I have one DbContext and I create a class variable that instantiates a database context object (in Controller), what happens then with this DbContext? Does it create in memory separate space for each of my entities? In my case, when I have 150 entities it would not be very effective. Am I wrong?
I will be using my DbContext in many Controllers. Is it a good idea to create a MainController (where I create new DbContext), which will be inherited by the rest of the Controllers? Because this allows others to have access to the same Context.
What is the best practise for disposing my DbContext? I've read that it is good practice to use dependency injection. But in this way I will have to inject context to every of my controllers. Which dependency injection way is the most popular and used now?
Really need your advice. It will give me more insight to this piece of development.
It is fine to have one DbContext. If you have many you just need to ensure all the entities you need exist in the that context. For example, if you retrieve a Person from the database and their related Address, then both the Person and Address have to exist in the same DbContext.
I've not tried using multiple DbContext instances, but one thing to look out for is if you include the same table in multiple contexts you could end up with classes with similar names or maybe conflicts. For example, if you include Person in two contexts, then each context will attempt to create a class named Person.
When you create a DbContext it will only create objects for the data you retrieve from the database. So if you request one row from a Person table, then only one Person object will be created. If you request 100 rows, then 100 instances will be created.
There are really two options. One, create a new instance in each action, do your work, then save it. Or, create a DbContext in your constructor and reuse that throughout the class.
This depends one what you choose in point #3. If you pass it into the constructor, then implement IDisposable and release it in there. If you create a new one in each action, then ensure it gets disposed using the using statement.
For dependency injection there are a number of options, tutorials, etc, on how to do this in ASP.NET MVC. I personally use Autofac, and related MVC extensions, and pass a new instance of the DbContext into each controller.
150 Entities is not a huge DbContext, but it is above the size where EF starts to exhibit performance issues in the initialization of the first DbContext. If you can logically separate your entities into areas of responsibility (called a bounded context) then you might consider using more than one DbContext. Also, does your app need to use all those entities? If not, you may be able to simplify things. Also note, you need at least EF6 to make this work effectively, previous versions of Entity Framework had issues with multiple contexts.
You also have to be careful when using multiple contexts. Many people get into trouble because they get an entity from one context, but then call save changes on a different one, and then don't understand why their changes are not saved. Or, they try to add an entity retrieved from one to another, which you can't do. Multiple contexts make things more complicated, so make sure you want to take on that complexity before you split it up.
Don't worry about the amount of memory your DbContext uses, so long as you are properly disposing of it. The amount of memory will be minimal unless you actually load objects from all of those tables.
I consider a common base controller to be a code smell. It's usually completely unnecessary, and it usually ends up becoming a dumping ground for every piece of code you think you want to share, which violates the Single Responsibility Principal. On top of that, you shouldn't be doing data access in your controllers anyways. You should have a service layer of some sort or business layer that call into a data access layer. Properly segregating your concerns is a key part of designing a good MVC application.
Yes, Dependency Injection is a good practice. I'm not sure what you mean by "have to inject into all my controllers". The whole point of dependency injection is to inject your dependencies, so the concept of "having to" makes it seem like you're trying to avoid the very thing you're trying to do.
Dependency Injection is a principle. There are many ways to achieve this principle, and which way you use depends entirely on your own preferences and requirements. We can't tell you what's "best" other than to make sure you're following the principle, and not a specific technology.
Regarding the dbcontext question:
I would go with multiple dbcontext (bounded contexts).
One problem with single big dbcontext is the loading and the Initializing time as it will map all the entities and this increases when your entities number increase in your context.
Now your project must consist of modules and this where you can divide your big dbcontext into small db contexts that covers all what each individual module needs to work with the database, for example let's say that your project has two modules (membership and billing or financial) for customer/person entity, you will find that when you deal with person in the membership module you need all his details but not full details of his invoices, and when you deal with the person in the billing module you will need all his invoices deatils but not his full personal information, here you can create 2 dbcontexts one for each module with person entity contains what that module needs from the person entity.
Julie lerman has a good article about dbcontext with Entity-framework that start with to get more details about what I am trying to describe here,
https://msdn.microsoft.com/en-us/magazine/jj883952.aspx
Hope this helps

Shouldn't Grails GORM calls be in the service and not controller layer?

I'm trying to decide, according to Grails best practices and MVC patterns, when is the correct time to introduce a Service and not keep fattening controllers. I find it somewhat conflicting, what I've read about best practices and what appears to be common practice, so would love to hear what others think about this.
With GORM calls in mind, I would have expected that anything to do with GORM should really go into a service. Although I don't practice this myself, especially when writing very basic controller methods like show that simply perform a get() on a domain class and then render a view to show the details of the retrieved object.
However, after following books like 'Clean Code' and similar books, well maintained code should be cohesive and methods should ideally perform a single task only. So in the perfect world, would the show method in a controller be responsible only for determining the object to display before rendering a view? The retrieval from the database could go into a method in the database that's sole task is to retrieve from the DB and throw an exception if not found etc.
But yes, this does somewhat seem like overkill.
So taking the step a bit further, the create() or update() methods. Again currently Grails' generated code puts everything into the controller, no use of a service at all.
So when would the recommended point be that we need to use a Service? Is it only when something transactional has to take place, for instance, on a create() call, we might also want to write a record to a Log file to keep an audit log of sorts. Surely this warrants a service?
I'd love to hear what others feel is the correct time to introduce services, I imagine it differs greatly person to person.
I recommend you this post: http://www.infoq.com/articles/grails-best-practices
We are creating static methods in Domain class to encapsulate queries. Service are used only for transactional operations or very complex queries with multiple domains interaction. Controllers simply call domains or services methods.

When should I consider implementing a Service in Grails?

I'm new to Grails and web development. I started doing a project on Schedule management website stuff. I came across the Service concept that is provided by Grails. I understood the concept, but still I have confusion on when to use services.
For example, I need to implement a search module, where the manager can search for a user to find his schedules. In this case it will be good to implement it as a controller or as a service?
So,
When and where should I use Service?
To add to Grooveek's answer;
It is also nice to use Services to keep your Controllers nice and clean.
So Views just render data to the screen, Domain objects store state, Controllers route the user around the application, and Services perform the work.
I don't have enough reputation to comment on an answer or vote up so I have to provide an answer that really should be a comment. Anyways...
+1 on #tim_yates answer. Gotta love thin controllers. 2 things that I would add to the description of a controller:
Would be to translate parameters from the browser before hitting a service (e.g. Date, number, etc.)
Would be to translate data returned from services into something consumable for the views.
For me, ideally, services would never deal with translating a String parameter to it's inherent type. Or deal with building a model to be displayed on a view.
What and where I should use Service?
When you want your controller do to something that may be reused by other controllers
In our application we're doing a functional separation of service. We have a CorePersistanceService, which provides method to create, delete, update and manipulate Core Domain Classes (core for us).
I think persistance services are a good way to reuse GORM code throughout Grails code. You can create method in domain classes, but I don't like that, it's way less maintanable I think
We have a PDFService class for our PDF creation, a SolrService which connect to Solr, a Statisticservice that gather all our methods which collects statictics on our datas
Services in Grails are a manner to gather methods around a particular functional theme, in order to give possibility to reuse them in controllers (I forgot to mention our SecurityService, which is a pretty good Cross-Applications Example)

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.

Architecting ASP.net MVC App to use repositories and services

I recently started reading about ASP.net MVC and after getting excited about the concept, i started to migrate all my webform project to MVC but i am having a hard time keeping my controller skinny even after following all the good advices out there (or maybe i just don't get it ... ).
The website i deal with has Articles, Videos, Quotes ... and each of these entities have categories, comments, images that can be associated with it. I am using Linq to sql for database operations and for each of these Entities, i have a Repository, and for each repository, i create a service to be used in the controller.
so i have -
ArticleRepository
ArticleCategoryRepository
ArticleCommentRepository
and the corresponding service
ArticleService
ArticleCategoryService ...
you see the picture.
The problem i have is that i have one controller for article,category and comment because i thought that having ArticleController handle all of that might make sense, but now i have to pass all of the services needed to the Controller constructor. So i would like to know what it is that i am doing wrong. Are my services not designed properly? should i create Bigger service to encapsulate smaller services and use them in my controller? or should i have an articleCategory Controller and an articleComment Controller?
A page viewed by the user is made of all of that, thee article to be viewed,the comments associated with it, a listing of the categories to witch it applies ... how can i efficiently break down the controller to keep it "skinny" and solve my headache?
Thank you!
I hope my question is not too long to be read ...
This is the side effect of following the Single Responsibility Pattern. If each class is designed for only one purpose, then you're going to end up with a lot of classes. This is a good thing. Don't be afraid of it. It will make your life a lot easier in the long run when it comes to swapping out components as well as debugging which components of your system aren't working.
Personally, I prefer putting more of my domain logic in the actual domain entities (e.g. article.AddComment(comment) instead of articleCommentService.AddComment(article, comment)), but your approach is perfectly fine as well.
I think you are headed in the right direction. The question is how to instantiate your services? I'm no MVC.NET guru, but have done plenty of service oriented Java projects and exactly the pattern you are discussing.
In Java land we would usually use Spring to inject singleton beans.
1) You can do the same thing in .NET, using dependency injection frameworks.
2) You can instantiate services as needed in the method, if they are lightweight enough.
3) You can create static service members in each controller as long as you write them to be threadsafe, to reduce object churn. This is the approach I use in many cases.
4) You can even create a simple, global service factory that all controllers access, which could simply be a class of singletons.
Do some Googling on .NET dependency injection as well.

Resources