Home > Back-end >  How do I connect a Razor Pages ASP.NET app to an already existing, not local MSSQL database?
How do I connect a Razor Pages ASP.NET app to an already existing, not local MSSQL database?

Time:06-03

I want to create a Razor Pages app where I would display the entries from a database. What am I supposed to put in the Connection String? I have the login to this database and the server.

And after I connect to it, how do I access it and simply display all the rows from the db in a page?

CodePudding user response:

There are a few things you should consider in order to access entities from DB in Razor Pages.

  1. Set the Connection String in appsettings.json

local:

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=XXXXXXX;Trusted_Connection=True;"
  },

remote:

"ConnectionStrings": {
    "DefaultConnection": "Server=xxx.xxx.xxx.xx;Database=XXXXXXX;User Id=yourUsername;password=yourPassword;Trusted_Connection=False;MultipleActiveResultSets=true;"
  }
  1. Add DB Context class that inherits DBContext ex. "YourDBContext"
public class YourDBContext: DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
      optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
    }
}
  1. Add DbContext to app services
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<YourDBContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

Than you can use Dependency Injection and access entity in your page via context:

public class IndexModel : PageModel
    {
        YourDBContext_context;

        public IndexModel(YourDBContext context)
        {
            _context = context;
        }

 public async Task<IActionResult> OnPostAsync()
        {
            IList<Blog> entities = await _context.Blogs.ToListAsync();
  ....

CodePudding user response:

There is a tool for working with databases EntityFramework.

You can use this article .

It answers all your questions about the connection string and display on the page.

  • Related