gpt4 book ai didi

sql-server - 如何使用 Entity Framework Core 进行迁移,通过 ASP.NET CORE MVC 连接到现有的 Azure SQL 数据库?

转载 作者:行者123 更新时间:2023-12-03 06:57:24 33 4
gpt4 key购买 nike

我有一个使用 Azure 应用服务以及 SQL 服务器和 SQL 数据库的应用程序,这些应用程序连接到我在 asp MVC 上的 Web 应用程序。我已使用分布式 Sql Server 缓存作为数据库上的表,到目前为止,一切运行良好并且相互连接。现在我想做两件事:

  • 将 Entity Framework 添加到我的应用程序中(我已经拥有数据库并且连接字符串)
  • 运行迁移 – 在我发布我的应用程序之后(如果我添加了例如新行或新

表,现在我有新版本)我不确定如何做这些事情,我查阅了很多指南但找不到答案。我发现了一篇与我的类似的帖子 – 但使用的是 azure 函数 - here。如果有人可以帮助我完成我需要遵循的步骤(就像他们在那篇文章中所做的那样)以获得 Entity Framework 和迁移,我将不胜感激。

这是我的代码:

程序.cs-

using Microsoft.Extensions.Azure;
using Azure.Identity;
var builder = WebApplication.CreateBuilder(args);

if(!builder.Environment.IsDevelopment())
builder.Configuration.AddAzureKeyVault(new Uri(Environment.GetEnvironmentVariable("VaultUri")), new DefaultAzureCredential());

builder.Services.AddControllersWithViews();
builder.Services.AddAzureClients(clientBuilder =>
{
clientBuilder.AddBlobServiceClient(builder.Configuration["storage:blob"], preferMsi: true);
clientBuilder.AddQueueServiceClient(builder.Configuration["storage:queue"], preferMsi: true);
});

builder.Services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = builder.Configuration.GetConnectionString("db");
options.SchemaName = "dbo";
options.TableName = "_Cache";
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();

家庭 Controller :

namespace WebAppAzure.Controllers
{
public class HomeController : Controller
{
private readonly BlobServiceClient storage;
private readonly ILogger<HomeController> logger;
private readonly IDistributedCache cache;

public HomeController(BlobServiceClient storage, ILogger<HomeController> logger,
IDistributedCache cache)
{
this.storage = storage;
this.logger = logger;
this.cache = cache;
}

public IActionResult Index()
{
var containerClient = storage.GetBlobContainerClient("public");
var blob = containerClient.GetBlobClient("image.jpeg");
var model = blob.Uri.ToString();

return View(model: model);
}

public IActionResult Privacy()
{
var stringModel = DateTime.Now.ToString();
cache.SetString("name", stringModel);
return View(model: $"SET: {stringModel}");
}

public IActionResult About()
{
var stringModel = cache.GetString("name");
return View(model: $"GET: {stringModel}");
}


[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}

最佳答案

  • 向我的应用添加 Entity Framework (我已经拥有数据库和连接字符串)

使用以下代码添加 Entity Framework 并上传到azure应用程序服务并运行迁移命令来迁移数据库。

项目中的DBcontext文件。

using Microsoft.EntityFrameworkCore;
using WebApplication_72783922.Entity;

namespace WebApplication_72783922
{
public class DbConnectionEntity : DbContext
{
public DbConnectionEntity()
{

}
//string connectionString = Environment.GetEnvironmentVariable("ConnectionStrings:dbcon").ToString();
public DbConnectionEntity(DbContextOptions<DbConnectionEntity> options)
: base(options)
{

}
public virtual DbSet<Users> users { get; set; }
public virtual DbSet<department> Departments { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Server=xxxx;Initial Catalog=database;Persist Security Info=False;User ID=adminserver72783922;Password=xxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;");
}
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
}

Program.cs 文件代码。

using Microsoft.Extensions.Azure;
using Azure.Identity;
using Microsoft.Extensions.Configuration;

var builder = WebApplication.CreateBuilder(args);

if (!builder.Environment.IsDevelopment())

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = "Server=xxxx;Initial Catalog=database;Persist Security Info=False;User ID=adminserver72783922;Password=xxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
options.SchemaName = "dbo";
options.TableName = "_Cache";
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
  • 运行迁移 - 在我发布应用后
Enable Migration using this command on Package Manager Console enable-migrations
Then add-migration InitialCreate
Then create migrationadd-migration test-v1
update database update-database -verbose

enter image description here

关于sql-server - 如何使用 Entity Framework Core 进行迁移,通过 ASP.NET CORE MVC 连接到现有的 Azure SQL 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72783922/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com