0

Working on Migrating .NET Framework to .NET core 6. I am trying to run the application which is not able to read the connection string from appsettings.json file. I have shown the appsettings.json file as well. Please let me know what I need to do. Old application reads from web.config file.

Context File

 public partial class PayMyRentEntities : DbContext
  {        

    public PayMyRentEntities()
        : base("name=PayMyRentEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Category> Categories { get; set; }
    public virtual DbSet<Hospital> Hospitals { get; set; }
    public virtual DbSet<LookupType> LookupTypes { get; set; }
    public virtual DbSet<LookupValue> LookupValues { get; set; }

  }

Appsetting.json

   {   

   "WebApiPublishUrl": "http://localhost:61330/",
     "ConnectionStrings": {
    "PayMyRentEntities": "metadata=res://*/PMR.csdl|res://*/PMR.ssdl|res://*/PMR.msl;provider=System.Data.SqlClient;provider connection string=\u0022data source=ACDSK3;initial catalog=Phnix;user id=hyd3;password=hyd3;integrated security=false;MultipleActiveResultSets=True;App=EntityFramework\u0022"

  }
}

Runtime Error :

enter image description here

User
  • 1,334
  • 5
  • 29
  • 61
  • What happens if you pass just "PayMyRentEntities" without the "name=" part? – Steve Dec 20 '22 at 10:42
  • I get the below error: "System.Data.Entity.Infrastructure.UnintentionalCodeFirstException: 'The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly."@Steve – User Dec 20 '22 at 10:44
  • 1
    Please refer to this [Docs](https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/working-with-sql?view=aspnetcore-7.0&tabs=visual-studio) to learn how to read `connectstring` in asp.net core, You can also refer to this [issue](https://stackoverflow.com/questions/72946724/whats-the-best-method-to-access-configuration-in-net-6/72946867#72946867) to learn how to bind data from appsetting.json to a model. – Xinran Shen Dec 21 '22 at 01:49

2 Answers2

1

Since you are using .net core 6, it's time for you to get to know dependency injection.

  1. Register the db in your startup

    builder.services.AddPooledDbContextFactory<PayMyRentEntities>((serviceProvider, builder) =>
        {        var config = serviceProvider.GetService<IConfiguration>()!;
                _ = builder
                    .UseSqlServer(config.GetConnectionString("PayMyRentEntities")).EnableServiceProviderCaching(false);
            },
            poolSize: 32)
    
  2. Then get the registered options for your class

    public PayMyRentEntities(DbContextOptions options)
        : base(options) {}
  1. After you set everything up, let .net handle your constructors
public sealed class SomeDotnetClass{
  private readonly PayMyRentEntities _context;
  public SomeDotnetClass(PayMyRentEntities context){
  _context = context;
 }
}
  1. Of course for this to work you have to register your class as well.
builder.services.AddScoped<SomeDotnetClass>()

This way you ensure that your db connection will be .net managed and for every API endpoint gets its own unique connection until the endpoint finishes its work. And the code readability is also maintained.

Alex Cr
  • 431
  • 5
  • 8
1

1)Program.cs

builder.Services.AddDbContext<PayMyRentEntities >(options => { options.UseSqlServer(builder.Configuration.GetConnectionString("DefualtConnection")); }); 2)DbContext:

public class PayMyRentEntities : DbContext
    {
        public PayMyRentEntities (DbContextOptions<PayMyRentEntities > options) : base(options)
        {
        }
    }

3)appsettings.json

"ConnectionStrings": {
    "DefualtConnection": "Data Source=.; Initial Catalog = nameDatabase;  Integrated Security=True; user id=hyd3;password=hyd3"
  }
azita
  • 11
  • 3