繁体   English   中英

如何将 Razor Pages ASP.NET 应用程序连接到现有的非本地 MSSQL 数据库?

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

我想创建一个 Razor Pages 应用程序,在其中显示数据库中的条目。 我应该在连接字符串中放入什么? 我有这个数据库和服务器的登录名。

在我连接到它之后,我如何访问它并简单地在页面中显示数据库中的所有行?

为了从 Razor Pages 中的 DB 访问实体,您应该考虑一些事项。

  1. 在 appsettings.json 中设置连接字符串

当地的:

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

偏僻的:

"ConnectionStrings": {
    "DefaultConnection": "Server=xxx.xxx.xxx.xx;Database=XXXXXXX;User Id=yourUsername;password=yourPassword;Trusted_Connection=False;MultipleActiveResultSets=true;"
  }
  1. 添加继承 DBContext ex 的 DB Context 类。 “你的数据库上下文”
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. 将 DbContext 添加到应用服务
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<YourDBContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

您可以通过上下文在页面中使用依赖注入和访问实体:

public class IndexModel : PageModel
    {
        YourDBContext_context;

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM