简体   繁体   中英

Error in Migration (DBCONTEXT File) in EF CodeFirst for NetCore for Winforms

I work with EF CodeFirt in NET Framework (Winforms) and NET Core (Web) without problems.

But with EF CodeFirst i have a error when throw a new migration:

System.NullReferenceException: Object reference not set to an instance of an object. at Data.AppDbContext.OnConfiguring(DbContextOptionsBuilder optionsBuilder) in C:\xxx\xxx\xxx\xxx\xxx\xxx\Data\AppDbContext.cs:line 29

<connectionStrings>
    <add name="AppDbContext" connectionString="<ConnectionString>"/>
</connectionStrings>

APPDBCONTEXT

public class AppDbContext : DbContext
    {        
        public DbSet<Unit> Units { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
        optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["AppDbContext"].ConnectionString);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.ApplyConfiguration(new UnitConfiguration());            
        }
    }

Because is WINFORMS don't exists STARTUP.CS or APPSETTINGS.JSON for configure how a service, I don't know what do.

I try many searches and many solutions in the web but the error persist.

I resolved the problem with help Karen Payne sample and support from Guru Stron . Thanks!!

The problem was in OnConfiguring method because for any reason the ConnectionString in method UseSqlServer are NULL.

If i read from APP.CONFIG file in windows form the value is correct but in OnConfiguring method are NULL.

The solution (no the best solution) was use one string for ConnectionString parameter and Migration work.

Now wait read ConnectionString parameter from APP.CONFIG file and complete the DbContext class.

Attach the code

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; //
            string connectionString = "Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=REF_SIGIPRO;Integrated Security=SSPI;";
            if (!optionsBuilder.IsConfigured)
                optionsBuilder.UseSqlServer(connectionString);
        }

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