简体   繁体   中英

DB Context is created every time I call an Action in ASP.NET MVC

I faced a problem while creating my Web Application. My goal is to create a Database each time I run my app. Here's how I do it. My Context class:

namespace MyWebApplication.Data
{
    public class MediaPlayerContext : DbContext
    {
        public DbSet<TrackEntity> TrackContextEntities { get; set; }
        public DbSet<AlbumEntity> AlbumContextEntities { get; set; }
        public DbSet<ArtistEntity> ArtistContextEntities { get; set; }
        public DbSet<BandEntity> BandContextEntities { get; set; }

        public MediaPlayerContext(DbContextOptions<MediaPlayerContext> options) : base(options)
        {
            MediaPlayerInitializer.Initialize(this);
        }
    }
}

Initializer class:

namespace MyWebApplication.Data
{
    public class MediaPlayerInitializer
    {
        public static void Initialize(MediaPlayerContext context)
        {
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            ArtistEntity DevonPortielje = new ArtistEntity()
            {
                Name = "Devon Portielje"
            };

//... at this part of code I create all my Artists, Bands, Tracks and Albums

            context.ArtistContextEntities.Add(DevonPortielje);

            context.SaveChanges();
        }
    }
}

I then use Repository class to manipulate my DbSet's

public class Repository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity
    {
        private readonly DbSet<TEntity> contextDbSet;

        public Repository(MediaPlayerContext context)
        {
            contextDbSet = context.Set<TEntity>();
        }
//... some Repository methods

And Unit of Work to wrap my Repositories

public class UnitOfWork : IUnitOfWork
    {
        private readonly MediaPlayerContext context;
        public IRepository<AlbumEntity> AlbumRepository { get; }
        public IRepository<ArtistEntity> ArtistRepository { get; }
        public IRepository<BandEntity> BandRepository { get; }
        public IRepository<TrackEntity> TrackRepository { get; }

        public UnitOfWork(MediaPlayerContext context, IRepository<AlbumEntity> albums,
            IRepository<ArtistEntity> artists, IRepository<BandEntity> bands,
            IRepository<TrackEntity> tracks)
        {
            this.context = context;
            AlbumRepository = albums;
            ArtistRepository = artists;
            BandRepository = bands;
            TrackRepository = tracks;
        }

        public void Save()
        {
            context.SaveChanges();
        }
    }

And after all of that I use Unit of Work in my Business Logic Services eg

    public class BandService : IBandService
    {
        readonly IUnitOfWork UnitOfWork;

        public BandService(IUnitOfWork unitOfWork)
        {
            UnitOfWork = unitOfWork;
        }

//... Service methods

And finally I use those Services in my Controller:

    public class MediaPlayerController : Controller
    {
        IBandService BandService;
        IAlbumService AlbumService;
        ITrackService TrackService;

        public MediaPlayerController(IBandService bandService, IAlbumService albumService,
            ITrackService trackService)
        {
            BandService = bandService;
            AlbumService = albumService;
            TrackService = trackService;
        }

//... Controller ActionResult Methods that return Views

I add my Context to services collection in Startup.cs file

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<MediaPlayerContext>(opt =>
                opt.UseSqlServer(Configuration.GetConnectionString("MediaPlayerDatabase")));

//...

The problem is that every time a new View is open a new Database is created because of these lines in my Initialize method.

            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

But I can't find any other possible way to create my database (SetInitializer is not accessible anymore) and no change in my database will ever be reflected since it's always deleted and created anew. What do I do? Thanks in advance.

I can see that your MediaPlayerInitializer.Initialize() method is static, you could create a static bool field and change it the first time to true and check it's value. Something like this:

private static bool initialized = false; // I know false is not needed

public static void Initialize(MediaPlayerContext context)
{
    if (initialized) {
        return;
    }

    context.Database.EnsureDeleted();
    context.Database.EnsureCreated();

    ArtistEntity DevonPortielje = new ArtistEntity()
    {
        Name = "Devon Portielje"
    };

    //... at this part of code I create all my Artists, Bands, Tracks and Albums
    context.ArtistContextEntities.Add(DevonPortielje);

    context.SaveChanges();

    initialized = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM