If I try "Add-Migration" with the follow all works well

问题描述 投票:0回答:1
But I tried to move the connection string to app.config and modify the above code as follow:

I also added "using System.Configuration;"

    public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
         => options.UseSqlServer(@"Server=MyServer;Database=MyDb;User Id=MyUser;Password=MyPsw");   
}

App.Config:

 public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
         => options.UseSqlServer(ConfigurationManager.ConnectionStrings["db"].ConnectionString);
}

But in that case it doesn't work and when I try the "Add-Migration" the operation fails and in the PMC appears "Object reference not set to an instance of an object.". What could the problem be?

(I know storing User

    <?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <connectionStrings>
    <add name="db"
         providerName="System.Data.SqlClient"
         connectionString="Server=MyServer;Database=MyDb;User Id=MyUser;Password=MyPsw"/>
  </connectionStrings>

</configuration>

If I try "Add-Migration" with the follow all works well public class BloggingContext : DbContext ...

public class BloggingContext : DbContext {

Add Startup.cspublic void ConfigureServices(IServiceCollection services) {services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); }
c# sql-server entity-framework connection-string database-migration
1个回答
0
投票

Here is how i got the ConnectionString. Not sure if this is working for you.

    public BloggingContext (DbContextOptions<BloggingContext> options) : base(options)
    {

    }
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

App.config

DBContext

0
投票

<connectionStrings>
<add name="con" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=PRWSolution2020;Integrated Security=True" providerName="System.Data.SqlClient"/>

我想通过一步一步的学习EF的东西,从今天早上开始我就被卡在这上面了:-。

© www.soinside.com 2019 - 2024. All rights reserved.