dbContext配置初始化问题

时间:2019-04-15 15:12:43

标签: c# entity-framework

当我创建DbContext时,它会跳过初始化程序。我启用了迁移,添加了初始迁移,并通过程序包管理器更新了数据库。前两个步骤成功完成,但是当update命令尝试初始化我的数据库时,它返回空引用异常。

上下文类:

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());
        }
    }`

配置类:

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();
        }
    }

我的自定义初始化程序的Seed()等于配置的。它继承了DropCreateDatabaseAlways<>

当我尝试向DbContext添加元素时抛出异常。 错误信息:

  

System.NullReferenceException:对象引用未设置为实例   一个对象。在DAL.Migrations.Configuration.Seed(MusicContext   上下文中)   D:\ Work \ Courses \ Raindrop \ DAL \ Migrations \ Configuration.cs:第105行
  在   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   endingMigrations,字符串targetMigrationId,字符串lastMigrationId)
  在   System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1   endingMigrations,字符串targetMigrationId,字符串lastMigrationId)
  在System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String   targetMigration)   System.Data.Entity.Migrations.DbMigrator。<> c__DisplayClasse.b__d()   在   System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(动作   mustSucceedToKeepDatabase)   System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(操作   mustSucceedToKeepDatabase)   System.Data.Entity.Migrations.DbMigrator.Update(字符串   targetMigration)   System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String   targetMigration)   System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()   在System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()   对象引用未设置为对象的实例。

第105行的代码:context.Albums.Add(alb1);

1 个答案:

答案 0 :(得分:0)

有3个问题:

  1. 我尚未指定User的{​​{1}}不可为空的字段。
  2. 我的JoinDate具有私有集属性。这导致从DbContext引发NullReferenceException。
  3. 我在对象之间指定了错误的引用。