C# Entity Framework 4.3 DbContext - c#

Im working on a MVC application, and was just wondering.. Should I be using the singleton pattern on my dbcontext object or is it safe to just instantiate one in every controller needed ?

You should not use a singleton pattern. Use one DbContext for one unit of work. The controller seems like a reasonable place to instantiate the context.

Related

How does Entity Framework Core implement code first?

I’m trying to learn how Entity Framework core uses C# classes to create the DbContext model. I assume it discovers types based on DbSets then calls the same model builder that is passed to OnSchemaCreating, I just can’t find the code/logic in the repository that does this (or perhaps there is another approach). Can anyone explain how this is done and point to the source code that does this?
Smit Patel from the ASP.NET team pointed me to the answer. There is a ModelSource abstraction that takes both a DbContext as well as some conventions. It customizes the the model based on DbSets on the DbContext class by simply adding an entity type for each DbSet, the remaining property/key/index configurations are all done by conventions.

ASP.NET Identity DBContext or Site DB Context?

I've been kind of out of the .net game for a while and I wanted to try the different new technologies.
I set up a site that uses code first migrations with EF 6 and MVC. The DBContext is created in my DAL and I'm using a repository / unit of work / n-tier implementation. I've created a User entity that holds profile information and a DBContext, let's call it SiteDbContext.
Now I'm at the MVC part and I'm trying to figure out the ASP.NET Identity. I have a few questions:
1) Should I use the ApplicationDBContext created in the UI along with SiteDbContext or dispose the ApplicationDBContext and use SiteDbContext (and just make sure it inherits IdentityDbContext)?
2) If I use the same DBContext, will it be a problem if I create a dependency on the asp.net identity in my DAL layer? Entity Layer (for ApplicationUser)? I don't want to create a dependency on my DAL regarding the DBContext so how would I supply it to the OwinContext?
3) I would like to use different DBContexts but I'm wondering how I'd make navigation properties to my User to the ASP.NET Identity user, vice versa etc.
Are there example projects I can download that implement multiple DBContexts or combine preexisting DBContexts with the ApplicationDBContext?
Thanks!
Eitan

Ramifications of using DBContext with Dependency Injection

I'm still kind of new to using dependency injection to manage my DBContext in an ASP.NET MVC application I'm writing.
I'm attempting to follow the approach outlined in the article Managing Entity Framework DbContext Lifetime in ASP.NET MVC. Basically, this approach says to use Ninject and dependency injection and to add my DBContext as a parameter to the constructor in my controllers.
Further, I am implementing this in a base controller, or which all my controller classes will be derived.
This is working, but I'm hitting on the following issues.
This approach requires that every derived controller class also implements a constructor that accepts any arguments requires by my controller base class. Not only does this seem like a lot of extra typing that I must remember to add to any new derived class, but it also means that if I change the data passed to the constructor then I must modify the constructor in every derived controller class.
This gives me a DBContext for all my controller classes. But what about other classes in my model that need the DBContext? Should I need to manually pass the instance to the DBContext to all these classes? Or is there a way to use DI for each of these classes to get their own copy of the DBContext?
This approach requires that every derived controller class also
implements a constructor that accepts any arguments requires by my
controller base class. Not only does this seem like a lot of extra
typing that I must remember to add to any new derived class, but it
also means that if I change the data passed to the constructor then I
must modify the constructor in every derived controller class.
This is one of the approach (Heavy Controller) that you may choose to use EF into your application, IMO its not the cleanest approach. And you correctly noticed the drawbacks your self.
If we relate this approach to design principle, it breaks Single Responsibility Principle as controller is expected to do more (fetch or update DB) than just collecting the data and return the appropriate view with data. And how about business rules, would controller apply it, if you need to send an email, would controller does that as well. You ought to have another layer of business/service classes that are specifically designed for a set of requirement e.g. EmailHelper would send emails.
It also breaks Open Close Principle as you need to change the constructors every time you change the input parameter.
This gives me a DBContext for all my controller classes. But what
about other classes in my model that need the DBContext? Should I need
to manually pass the instance to the DBContext to all these classes?
As far as dependency injection is concerned one of the goal is, to inject the dependency where it is needed directly. If you have a model class that needs DbContext, you should inject it in your model class constructor (most DI framework support property injection as well but constructor remains favourite approach).
With DI Framework, you will configure the dependencies at one place (application initialization code) and then each class that need a dependency just accept it in constructor.
DI Container can be compared to a dictionary where key is interface and the value is a cooked object. Once its setup, you can anytime ask for any object by using the right key through out your application.
Or is there a way to use DI for each of these classes to get their own
copy of the DBContext?
The DI framework supports different ways of instantiation to allow controlling the lifetime of the instance. Typically, per request, per thread and singleton. More information here. If you want each controller to get a copy of DbContext, you can use per request configuration when you set up DbContext instantiation.
Alternate Solution:
Most of my MVC applications, I have had a service layer (set of classes that apply business rule). Each of these classes were injected with DbContext (not exactly a DbContext but IDataContext). The controllers were injected with the service class that they need to retrieve or update the data.
Have abstracted the DbContext behind IDataContext, I could setup a stub data context in my test or tomorrow if I want to switch from EF to NHibernate or something more smart DI Framework, i will just have to implement IDataContext and change the dependency initialization code.
Hope this helps.

asp.net mvc3 Code First (Database Singleton)

I am working on asp.net mvc using code first. I noticed that once i create a new controller, the controller template shows dispose overridden method that just has one job; dispose db variable created at the top of this controller.
I am thinking of changing this to use singleton pattern with my DBContext class.
I tried it and it worked fine. except that i needed sometimes to access database from global.asax. (sometimes) is throws an exception.
Have anyone thought to do the same? Any ideas?
Thank you
personally I would follow a completely different approach, see my answer here: https://stackoverflow.com/a/7474357/559144 I would not use Singleton and would not hardlink MVC which is a UI framework with the DAL (EF in your case).
about not using singleton, let the database handle concurrency; it's one of the things Database servers do the best ;-)
We use EF context as a singleton per http context. I also would not hard link EF with MVC, but you can still be sure that each http context deals with a single EF context instance by using dependency injection (we use Unity).
We also access the context in global asax to do db initialization and seeding for development. Again, you can use a DI container to get an instance of the EF context.
public interface IUnitOfWork : IDisposable
{
int SaveChanges();
}
public class MyEfContext : DbContext, IUnitOfWork
{
// your custom context code
}
Using a singleton-per-http-context lifetime for the IUnitOfWork dependency injection isn't an approach to help deal with concurrency in our case. We do it because when dealing with EF entities, we need to make sure all of the selects / inserts / updates / deletes always happen with the same context instance. EF does not let you attach entities to multiple contexts, and we use singleton per http context for this reason.

Entity Framework 4 ObjectContext GuideLines

I read in a previous article about how to resolve a solution by placing the ObjectContext of my Db in a property within HttpContext.Current.Items["Db"]; This works fantastic, however I have a question. Does this means that every time I use my repository I have to pass the ObjectContext within HttpContext.Current.Items or do I only need to do this when I am creating or updating an entity that has a reference to another entity.
Within my repository classes I have 2 ways of instantiating them, with a ObjectContext and without one in which the ObjectContext is created there within the entity.
You should share one context among all your repositories used in single HTTP request processing. You should also dispose context at the end of request processing. Generally your repository should not be dependent on HttpContext. The best way is to create ObjectContext outside of your repositories and always pass it to their constructor. You can also do that by using some IoC container like Windsor, StructureMap, Ninject or Unity.

Categories

Resources