如何使用ASP.NET Core MVC使用Entity Framework Core与迁移?

发布于 2025-02-11 02:48:29 字数 2996 浏览 0 评论 0原文

我有一个使用SQL Server和SQL数据库的Azure App Services的应用程序,该应用程序连接到ASP MVC上的Web应用程序。我已经使用了分布式SQL Server Cache作为数据库中的表,到目前为止,所有内容都运行良好并且相互连接。 现在我想做两件事:

  • 将实体框架添加到我的应用程序(我已经有数据库和 连接字符串)
  • 运行迁移 - 我发布了我的应用程序(如果我添加了 示例新线或新

表格,现在我有新版本) 我不确定如何做这些事情,我抬头看着许多指南,找不到答案。 I found a post similar to mine – but using azure functions -

这是我的代码:

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

家庭控制器:

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 });
        }
    }
}

I have an app using Azure App Services with SQL server and SQL database that are connect to my web app on asp MVC. I've used Distributed Sql Server Cache as a table on my database and so far everything is working well and connected to each other.
Now I want to do two things:

  • Add entity framework to my app (I already have the database and
    connection string)
  • Run migration – after I've published my app (If I've added for a
    example new line or new

table, now I have new version)
I'm not sure how to do those things , I've looked up on many guides and couldn't find an answer. I found a post similar to mine – but using azure functions - here
. I would appreciate it if someone can help me with the steps that I need to follow (like they did in that post) to get entity framework and the migration.

Here is my code:

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

Home 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: 
quot;SET: {stringModel}");
        }

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


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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

方觉久 2025-02-18 02:48:29
  • 将实体框架添加到我的应用程序(我已经具有数据库和连接字符串)

在下面的代码中使用代码添加实体框架并上传到Azure App Service并运行迁移命令以迁移数据库。

项目中的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();
  • 运行迁移 - 我发布了app
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

“

  • Add entity framework to my app (I already have the database and connection string)

Use below code for add Entity framework and upload to azure app service and run migration command to migrate database.

DBcontext file in project.

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 File code.

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();
  • Run migration – after I’ve published my app
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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文