【发布时间】:2023-03-03 14:45:01
【问题描述】:
为了连接到 ASP.NET Core 应用程序中的数据库,我们创建了一个 DbContext
namespace MyProject.Models
{
public class MyProjectContext : DbContext
{
public MyProjectContext (DbContextOptions<MyProjectContext> options)
: base(options){ }
public DbSet<MyProject.Models.Record> Record { get; set; }
}
}
在 Startup.cs 中我们这样做
public void ConfigureServices(IServiceCollection services) {
// Adds services required for using options.
//...
// Add framework services.
services.AddMvc();
services.AddDbContext<MyProjectContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyProjectContext")));
}
最后在我们的控制器中
namespace MyProject.Controllers
{
public class RecordsController : Controller
{
private readonly MyProjectContext _context;
public RecordsController(MyProjectContext context) {
_context = context;
}
// GET: Records
public async Task<IActionResult> Index() {
return View(await _context.Record.ToListAsync());
}
好的,所有这些都来自 VS 脚手架...
================================================ ===============
我现在要处理 AzureTables,所以我做了一个测试控制器
Startup.cs
public void ConfigureServices(IServiceCollection services) {
// Adds services required for using options.
...
// Register the IConfiguration instance which "ConnectionStrings" binds against.
services.Configure<AppSecrets>(Configuration);
HelloWorldController.cs
namespace MyProject.Controllers
{
public class HelloWorldController : Controller
{
CloudTableClient cloudTableClient = null;
public HelloWorldController(IOptions<AppSecrets> optionsAccessor) {
string azureConnectionString = optionsAccessor.Value.MyProjectTablesConnectionString;
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(azureConnectionString);
cloudTableClient = cloudStorageAccount.CreateCloudTableClient();
}
public async Task<string> ReadTables() {
CloudTable table = cloudTableClient.GetTableReference("themes");
StringBuilder response = new StringBuilder("Here is your test Table:");
var query = new TableQuery<DescriptionEntity>() {
SelectColumns = new List<string> { "RowKey", "Description" }
};
var items = await table.ExecuteQuerySegmentedAsync<DescriptionEntity>(query, null);
foreach (DescriptionEntity item in items) {
response.AppendLine($"Key: {item.RowKey}; Value: {item.Description}");
}
return response.ToString();
}
问题
如何以与 SQL 上下文相同的方式集成 Azure 表?我的意思是,对 Azure 表有相同的 3 个步骤:
- 创建 Azure 表上下文,
- 配置服务(通过 Startup.cs 中的 ConfigureServices(IServiceCollection)),
- 将“IAzureTable 上下文”传递给控制器的构造函数?。
我是完全的新手,非常感谢您提供步骤的代码示例。
例如,如何创建 Azure DBContext(如果需要的话)?
【问题讨论】:
-
现在控制器与实现问题紧密耦合。提取这些实现并将它们封装在抽象后面是一个好主意。这就是我从你的问题中收集到的。
-
我会另外提取接口并使用 DI/IoC 和依赖解析器,但真的不知道如何实现它......类似于这个的问题:stackoverflow.com/questions/24626749/…
-
问题中的代码正是我所指的。尝试尽可能抽象以避免耦合到实现问题并将其注入控制器。将 azure 表视为一个数据源,以后可以用其他一些实现来替换。
-
Try to abstract as much as possible=IAbstractRepositoryFactoryFactory<TFactory> -
知道怎么做,这就是问题的原因
标签: asp.net-mvc asp.net-core asp.net-core-mvc azure-table-storage asp.net-core-1.1