using multiple dbcontext for each business function - asp.net-mvc

I am using ASP.NET MVC5, entity framework in my web application. It is expected complex business logic so achieving separation in code based on an individual business concern is required. I am using Code First with existing database approach. I have created 3 ADO.NET Entity Data Model in design wizard. so separate dbContext with its model. My issue arise when i created 3rd dbContext which has one table share from one of the model i have created initially. the error is Metadata Exception was unhandle by user code. I believe is something to do with Meta data but not sure how to approach this problem?
what i am trying to achieve, if one webpage (one business function) to only two table, why load whole data in memory plus decoupling will improve maintainability and flexibility to extend application without disturbing existing code!

The key to using Bounded Contexts is use of
Ignore entity
modelBuilder.Ignore<MyUnNecessaryEntity>();
and/or
change the DataBAse initializer on a MINI context to none
Database.SetInitializer(new ContextInitializerNone<MyContext>());
I like teh idea of ONLY 1 context is responsible for keeping a set of tables consistent.
The other contexts can access those tables using the same POCO definitions. They can be a subset of pocs. The context is reduced and or has NO initializer.
There is a good article worth a read from Julie Lerman on MSDN on the topic of Bounded Contexts.

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

Domain Driven Design vs Database Driven Design for an MVC Web application

I am expanding/converting a legacy Web Forms application into a totally new MVC application. The expansion is both in terms of technology as well as business use case. The legacy application is a well done Database Driven Design (DBDD). So for e.g. if you have different types of Employees like Operator, Supervisor, Store Keeper etc and you need to add a new type, you just go and add some rows in a couple of tables and voila, your UI automatically has everything to add/update the new type of Employee.
However the seperation of layers is not so good.
The new project has two primary goals
Extensibility (for currently and future pipeline requirements)
Performance
I intend to create the new project replacing the Database Driven Design (DBDD) with a Domain Driven Design (DDD) keeping the Extensibility requirement in mind. However moving from a Database Driven Design to Domain Driven Design seems to inversely impact the Performance requirement if I compare it to the performance of the legacy DBDD application. In the legacy application any call for data from the UI would directly interact with the Database and any data would be returned in form of a DataReader or (in some cases) a DataSet.
Now with a strict DDD in place any call for data will be routed through the Business layer and the Data Access layer. This would mean each call would initialize a Business Object and a Data Access Object. A single UI page could need different types of data and this being a Web application each page could be requested by multiple users. Also a MVC Web application being stateless, each request would need initializing the business objects and data access objects each and every time.
So it seems for an MVC stateless application the DBDD is preferrable to DDD for performance.
Or there a way in DDD to achieve both, Extensibility that DDD provides and performance that DBDD provides ?
Have you considered some form of Command Query Seperation where the updates are through the domain model yet reads come as DataReaders? Full blown DDD is not always appropriate.
"Now with a strict DDD in place any call for data will be routed through the Business layer and the Data Access layer."
I don't believe this is true, and it's certainly not practical. I believe this should read:
Now with strict DDD in place, any call for a transaction will be routed through the business layer and the data access layer.
There is nothing that says you can't call the data access layer directly in order to fetch whatever data you need to display on the screen. It is only when you need to amend data that you need to invoke your domain model that is designed based on its behavior. In my opinion this is a key distinction. If you route everything through your domain model you will have three problems:
Time - it'll take you MUCH longer to implement functionality, for no benefit.
Model Design - your domain model will be bent out of shape in order to meet the needs querying rather than behavior.
Performance - not because of an extra layer, but because you wont be able to get the aggregated data from your model as quickly as you can directly from a query. i.e. Consider the total value of all orders placed for a particular customer - its much faster to write a query for this than to fetch all order entities for the customer, iterate over and sum.
As Chriseyre2000 has mentioned, CQRS aims at solving these exact issues.
Using DDD should not have significant performance implications in your scenario. What you worried about seems more like a data access issue. You refer to it as
initialize a Business Object and a Data Access Object
Why is 'initializing' expensive? What data access mechanisms are you using?
DDD with long-lived objects stored in a relational database is usually implemented with ORM. If used properly, ORM will have very little, if any, impact on performance for most applications. And you can always switch back the most performance-sensitive parts of the app to raw SQL if there is a proven bottleneck.
For what's it worth, NHibernate only needs to be initialized once on application startup, after that it uses the same ADO.NET connection pool as your regular data readers. So it all boils down to a proper mapping, fetching strategy and avoiding classic data access mistakes like 'n+1 selects'.

SubSonic 3, Entity Data Model (Entity Framework) or LINQ to SQL for ASP.NET MVC development?

Having used all of them (some more than others), I am still undecided on which could be the best to use (with .NET 3.5). What are the pro's and con's of each when developing?
SubSonic 3
Not enough samples/documentation (I know its a wiki and people can update it, but it can be tricky to track things down - e.g. where are the sample apps (WebForms, MVC (current version, rather than pre-3), WinForms)). Text Templates didn't work as expected when I first tried them. For example, it does not clean up the table names like SubSonic 2 did (removing/replacing spaces for example). Also, you cannot say which tables to include, just the ones you can exclude (in ActiveRecord.tt). Context.tt and Structs.tt generates code for all the tables (you would probably not want the 'aspnet_' ones, and probably some others (session tables) as well).
Saying that though (hope I'm not being too harsh), it is quite a good ORM to use, minor issues aside.
Entity Data Model (Entity Framework)
Visual Designer for setting up models. Syncs with database, might be considered a bit 'verbose' and hard to understand. There is fairly decent documentation though. Not gone that much further in depth though.
LINQ to SQL
Also has a designer for creating models. Simple to use. Less features than the other two. I also had to apply a hotfix for an obscure bug (wouldn't update when the model had foreign keys that were not of type int)
NHibernate
Looked at this in the past, but not that easy to set up compared to the above.
Any sample ASP.NET MVC apps using this?
Ideally I would want a framework that:
a) could generate the models from a database
b) support LINQ syntax
c) retrieve only the data that is needed (e.g. for paging)
d) allow data annotations
e) could generate the sql to update or create new tables in an existing database
MVC is presentation layer, ORM is Data layer
I don't think that ORM has anything so much to do with an MVC application. At least if you tier your application properly. Model in an MVC application is rather model of the presentation layer view. A view model through which controller and view communicate. Not necessarily data model. MVC project template is a bit confusing, since developers think that MVC model = data model. In any business application that is not completely trivial (like a single assembly simple application) this is not equal. And it's better that its not. Especially if we take into cosideration separation of concerns. We shouldn't rely on particular ORM classes in any layer other than data layer.
But if you intend to use DTOs in your MVC application (as view models) I suggest you use that ORM that creates partial classes, so you can easily add additional stuff on them (like attributes). Your data annotations can be written inside of a special metadata class that can be attached to your model class by a single class-level attribute.
Suggestion
But I suggest doing something else. Use a separate layer with POCOs that will be used on all layers and would have data annotations on them. This will make your presentation layer independent of data layer and your POCOs may also be presentation optimised (like having a class called UserRegistration for instance with two password properties - with repeated value as well). Your repository in your data layer would be responsible for POCO conversion so all layers will exchange data using POCOs only instead of using data objects.
ORMs and class generation
With Entity Framework you do get a very controllable environment to generate your classes from a data store schema. Unfortunately it's not the same with others. Generateion is not all-in, but can be controlled and manipulated manually as well (if you'd like to do TPH/TPT structures).
Similar with LINQ to SQL. I haven't used any other ORM but I guess LinqConnect may have it's own editor similar to EF Visual Studio editor, because I've been working with MySql connector from the same company and I've used their designer for entities because it was better than the one provided with Visual Studio 2008.
But you have tools that provide code generation (and you can get templates on the internet for various ORMs as well):
there's T4 built into Visual Studio that can generate code for you; You can as well fint templates for ORMs written in T4 that you can then easily customize. Or write your own acording to your needs (I've written enumeration generator from DB lookup tables in the past)
MyGeneration is open source and you can find lots of templates for it
CodeSmith is not free but is a proved product that I've used in the past with .netTiers template (before we had LINQ) which saved lots of time and worked perfectly

How can I extend the Model in ASP.NET MVC and Entity Framework?

In my first ASP.NET MVC applications, the model was a simple O/R mapping between a table and the classes, managed by the Entity Framework.
Now I would like to add some meat to this skeleton, and introduce business methods for the generated classes. What is the recommended approch to this in ASP.NET MVC (with Entity Framework)? My favorite would be solution which also can be used in a service layer, with no ASP.NET MVC references, so that the same domain logic also could be reused in a desktop client.
Technically, I think it should be possible to extend the generated classes in a way which preserves the additional business logic even if the O/R classes need to be refreshed. (This is more a question related to the Entity Framework however.)
Edit: Many thanks for the contributions, and the information about the next version of Entity Framework (4.0). Building two sets of classes, one auto-generated to represent the data in the persistency layer and one for the actual business logic sounds interesting.
Within MVC.Net, the model is the least clearly defined part. In my opinion, it's basically the rest of your application (i.e. anything not related to the View or the Controller). The O/R Mapping part of your application should probably be outside of the "Model" also, as this is more of a data layer. The Model, should really deal in business objects and create views of your data to pass to the View.
There are lots of differing opinions on this, but I think it's best not to think of MVC.Net as traditional MVC Architecture.
If you are using EF v1.0 right now, the Entity Framework is very intrusive into your application, which means that you cannot create POCO very easily. The way you can extend your model is by using the partial class. So when you refresh your model, the partial class you did will still be valid. The Entity Framework team realizes this is a problem , and have improved this in next version (EF V4.0).
NHibernate is much more friendly and allow you easily extend your business logic.
I really think this blog post by Jeremy D. Miller is very good at pointing out the problem.
Abstract your Business Layer out into another project, then pass an instance of it onto your mvc controller using something like structure map. You can then call this Business Layer from your controller to retrieve your business entities (Model) and pass them on to the UI. This will allow you to resuse your Business Layer in your desktop application.
Not only meat but also some clothes and a style could be added to this project to make it seem chic. It depends on the time you have for the project. If you have time, I could suggest you to get a look to TDD and the frameworks that could be used with TDD such as Castle, NUnit, Moq etc.
As you mentioned a service layer is a must for any project but with these kinds of frameworks you could design your architecture more robust.

ASP.NET MVC - model decision: how to design it?

This is concerning an enterprise application with a very generic database (all objects are identified using data in the database and internationalized/globalized/localized).
Make a model for Repository pattern, then make (generate 1:1) another model for DB access (LINQ2SQL or EF) and use the later as repository model data access layer?
Just use L2S/EF/NHibernate model directly, mapping model to DB and opening persistence layer?
Will this dual model idea (repository pattern) popup problems making dynamic stackable LINQ search queries possible when using L2S/EF model directly in a dual model environment?
Please advise.
As long as you are exposing IQueryable objects in your repository, you should have no problem stacking queries in the manner you suggest.
I would be cautious about using Entity Framework for this, since lazy loading is not supported in the way you might expect. Linq to SQL will handle lazy loading without problems.
For more information about lazy loading in the Entity Framework, see: http://www.singingeels.com/Articles/Entity_Framework_and_Lazy_Loading.aspx
Take a look at sharp architecture.
Regarding returning IQueryable from your repository objects, it is my opinion that doing such blurs a proper separation of concerns in your application. I'm all for working with IQueryable within your data access layer but once you start returning objects as IQueryable you provide the opportunity for your controllers and/or views to start meddling with data access. Such may even negatively impact the testability of your application as well.

Resources