简体   繁体   中英

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

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?

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

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