[英]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.我想创建一个 Razor Pages 应用程序,在其中显示数据库中的条目。 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.为了从 Razor Pages 中的 DB 访问实体,您应该考虑一些事项。
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;"
}
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);
}
}
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();
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.