简体   繁体   中英

DbContext Configuration initialization problem

When I create the DbContext it skips my initializer. I enabled migrations, added initial migration, updated the DB through the package manager. First two steps were successful, but when update command try to initialize my DB it returns null reference exception.

Context class:

public class MusicContext:DbContext
    {
        public DbSet<Album> Albums { get; private set; }
        public DbSet<Artist> Artists { get; private set; }
        public DbSet<Rating> Ratings { get; private set; }
        public DbSet<Song> Songs { get; private set; }
        public DbSet<User> Users { get; private set; }

        private static MusicContext s_instance;

        public MusicContext() : base("EntityDB")
        {
            Database.SetInitializer<MusicContext>(new MusicInitializer());
            var ensureDllIsCopied = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
        }

        private MusicContext(string conStr) : base(conStr)
        {
            Database.SetInitializer(new MusicInitializer());
            var ensureDllIsCopied = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
        }

        public static MusicContext GetContext(string conStr)
        {
            if(s_instance==null)
                s_instance = new MusicContext(conStr);
            return s_instance;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new AlbumConfig());
            modelBuilder.Configurations.Add(new ArtistConfig());
            modelBuilder.Configurations.Add(new SongConfig());
            modelBuilder.Configurations.Add(new UserConfig());
        }
    }`

Configuration class:

internal sealed class Configuration : DbMigrationsConfiguration<DAL.MusicContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(DAL.MusicContext context)
        {
            Artist art1 = new Artist()
            {
                Name = "Skillet",
                CareerStart = 1996 ,
                Albums =new List<Album>(),
                Songs =new List<Song>()
            };
            Artist art2 = new Artist()
            {
                Name = "Rammstein",
                CareerStart = 1993,
                Albums = new List<Album>(),
                Songs = new List<Song>()
            };
            Artist art3 = new Artist()
            {
                Name = "Sharleen Spiteri",
                CareerStart = 1988,
                Albums = new List<Album>(),
                Songs = new List<Song>()
            };

            Album alb1 = new Album()
            {
                Name = "Rosenrot",
                Year = 2005,
                Genre = "Industial Metal",
                Artists = new List<Artist>(),
                Songs = new List<Song>()
            };

            Album alb2 = new Album()
            {
                Name = "Comatose",
                Year = 2006,
                Genre = "Alternative Metal",
                Artists = new List<Artist>(),
                Songs = new List<Song>()
            };
            Song song1 = new Song()
            {
                Name = "Don't Die Before I Do",
                Year = 2005,
                Album = alb1,
                Artists = new List<Artist>(),
                Ratings = new List<Rating>(),
                Liked = new List<User>(),
                Filename = @"some filename"
            };
            Song song2 = new Song()
            {
                Name = "Whispers in the Dark",
                Year = 2006,
                Album = alb2,
                Artists = new List<Artist>(),
                Ratings = new List<Rating>(),
                Liked = new List<User>(),
                Filename = @"some filename"
            };
            art1.Albums.Add(alb1);
            art1.Songs.Add(song1);
            art2.Albums.Add(alb2);
            art2.Songs.Add(song2);
            art3.Songs.Add(song1);
            alb1.Songs.Add(song1);
            alb2.Songs.Add(song2);
            song1.Artists.Add(art1);
            song1.Artists.Add(art3);
            song2.Artists.Add(art2);

            User admin = new User() {
                Name = "Krakenus00",
                Role = "ADMIN",
                Ratings = new List<Rating>(),
                Liked = new List<Song>()
            };
            UserInfo ui = new UserInfo
            {
                Email = DataProtection.Encrypt("adminpoint"),
                PasswordStored = DataProtection.Encrypt("FullAccess"),
                User = admin
            };
            Rating rating = new Rating() { User = admin, Song = song2, Value = 5 };
            admin.Liked.Add(song2);

            context.Albums.Add(alb1);
            context.Albums.Add(alb2);
            context.Artists.Add(art1);
            context.Artists.Add(art2);
            context.Artists.Add(art3);
            context.Songs.Add(song1);
            context.Songs.Add(song2);
            context.Users.Add(admin);
            context.Ratings.Add(rating);

            context.SaveChanges();
        }
    }

My custom initializer's Seed() is equal to Configuration's. It inherits DropCreateDatabaseAlways<>

Exception throws when i try to add elements to the DbContext. Error info:

System.NullReferenceException: Object reference not set to an instance of an object. at DAL.Migrations.Configuration.Seed(MusicContext context) in D:\\Work\\Courses\\Raindrop\\DAL\\Migrations\\Configuration.cs:line 105
at System.Data.Entity.Migrations.DbMigrationsConfiguration 1.OnSeed(DbContext context) at System.Data.Entity.Migrations.DbMigrator.SeedDatabase() at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase() at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable 1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration) at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClasse.b__d() at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration) at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore() at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run() Object reference not set to an instance of an object.

Code on line 105: context.Albums.Add(alb1);

There were 3 problems:

  1. I have not specified User 's JoinDate not nullable field.
  2. My DbContext had private set properties. This caused throwing NullReferenceException from DbSet<>.Add() .
  3. I have badly specified references between my objects.

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