如何在.NET 7中使用Entity Framework Core初始化数据库

huangapple go评论68阅读模式
英文:

How to Intialize Database with entitycore in dotnet 7

问题

var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;

builder.Services.AddDbContext<TvMazeContext>(options =>
    options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    try
    {
        var context = services.GetRequiredService<TvMazeContext>();
        DbInitializer.InitializeAsync(context).Wait(); // Wait for initialization to complete
    }
    catch (Exception ex)
    {
        var logger = services.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "An error occurred creating the DB.");
    }
}

// Rest of your program.cs code
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
英文:

I have written a class like bellow that should initialize the database

using System.Diagnostics;
using TvApi.Models;
using TvApi.Services;

namespace TvApi.Data
{
    public static class DbInitializer
    {
        static List&lt;List&lt;Cast&gt;&gt; listedCasts;
        static List&lt;List&lt;ShowCast&gt;&gt; listedShowCasts;
        static List&lt;Show&gt; listedShows;

        public static async Task InitializeAsync(TvMazeContext context)
        {
            for (long i= 1;i &lt; 10; i++)
            {
                long ShowId = i;
                Show show = await Crawler.CrawlShowAsync(ShowId);
                listedShows.Add(show);
                List&lt;Cast&gt; casts = await Crawler.GetCastsAsync(ShowId);
                listedCasts.Add(casts);
                List&lt;ShowCast&gt; showCasts = new List&lt;ShowCast&gt;();
                foreach (var item in casts)
                {
                    showCasts.Add(new ShowCast(show.ShowId, item));
                }
                listedShowCasts.Add(showCasts);

            }

            context.Database.EnsureCreated();

            if (context.shows.Any())
            {
                return;   // DB has been seeded
            }

            
            foreach (Show s in listedShows)
            {
                context.shows.Add(s);
            }
            context.SaveChanges();

            foreach (List&lt;Cast&gt; castsList in listedCasts)
            {
                foreach(Cast cast in castsList)
                {
                    context.casts.Add(cast);
                }

            }

            foreach (List&lt;ShowCast&gt; showCastsList in listedShowCasts)
            {
                foreach (ShowCast showCast in showCastsList)
                {
                    context.showCasts.Add(showCast);
                }

            }

        }
    }
}

I am following the microsoft tutorial bellow to add the intializer to my startup.cs

Microsoft tutorial

However the program.cs there is different than mine:

//My version of program.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using TvApi.Data;

var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;

//Database
builder.Services.AddDbContext&lt;TvMazeContext&gt;(options =&gt;
options.UseSqlServer(configuration.GetConnectionString(&quot;DefaultConnection&quot;)));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

/*
 * My attempt to initialize
var host = CreateHostBuilder(args).Build();



IHost host; 
using (var scope = host.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    try
    {
        var context = services.GetRequiredService&lt;TvMazeContext&gt;();
        await DbInitializer.InitializeAsync(context);
    }
    catch (Exception ex)
    {
        var logger = services.GetRequiredService&lt;ILogger&lt;Program&gt;&gt;();
        logger.LogError(ex, &quot;An error occurred creating the DB.&quot;);
    }
}
*/

// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}


app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

What should I add to my version of the program.cs to correctly initialize my database during the startup?

答案1

得分: 1

从你的问题中,我认为你想在数据库中种子数据,所以这里有一个简单的演示可以适用于 .Net6 和 .Net7

public static class DbInitializer
{
    public static async Task InitializeAsync(ApplicationDbContext context)
    {
        List<SeedModel> seedDatas = new List<SeedModel>();
        seedDatas.Add(new SeedModel()
        {
            Name = "AAAA",
            Age = 2
        });
        seedDatas.Add(new SeedModel()
        {
            Name = "BBB",
            Age = 3
        });
        seedDatas Add(new SeedModel()
        {
            Name = "AAAA",
            Age = 2
        });

        await context.SeedModels.AddRangeAsync(seedDatas);
        await context.SaveChangesAsync();
    }
}

然后在 program.cs 中:

// ......
var app = builder.Build();
// ......
       
using (var scope = app.Services.CreateScope())
{
    // 通过 DI 解析 dbcontext
    var dbcontext = (ApplicationDbContext)scope.ServiceProvider.GetService(typeof(ApplicationDbContext));

    // 调用你的静态方法
    await DbInitializer.InitializeAsync(dbcontext);
}
// ......

现在,当你启动项目时,数据库将被初始化为一些数据。
英文:

From you question, I think You want to seed data in database, So here is a simple demo can fit .Net6 and .Net7

public static class DbInitializer
    {
        public static async Task InitializeAsync(ApplicationDbContext context)
        {
            List&lt;SeedModel&gt; seedDatas = new List&lt;SeedModel&gt;();
            seedDatas.Add(new SeedModel()
            {
                Name = &quot;AAAA&quot;,
                Age = 2
            });
            seedDatas.Add(new SeedModel()
            {
                Name = &quot;BBB&quot;,
                Age = 3
            });
            seedDatas.Add(new SeedModel()
            {
                Name = &quot;AAAA&quot;,
                Age = 2
            });

            await context.SeedModels.AddRangeAsync(seedDatas);
            await context.SaveChangesAsync();

        }
    }

Then in program.cs

//.......    
var app = builder.Build();    
//.....
   
using (var scope = app.Services.CreateScope())
{
    //Resolve dbcontext with DI help
    var dbcontext = (ApplicationDbContext)scope.ServiceProvider.GetService(typeof(ApplicationDbContext));

    //call your static method herer

    await DbInitializer.InitializeAsync(dbcontext);
}
//......

Now, When you start your project, Database will be initialized with some data.

如何在.NET 7中使用Entity Framework Core初始化数据库

huangapple
  • 本文由 发表于 2023年3月7日 17:13:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定