代码之家  ›  专栏  ›  技术社区  ›  Peter

种子列表导致EF核心为空

  •  0
  • Peter  · 技术社区  · 2 年前

    List 为空。

    [{"title":"Borja On Fleek \uD83D\uDD25","chapters":null,"id":1}]
    

    数据库上下文:

    using Core.Entities;
    using Core.Entities.BookAggregate;
    using Core.Entities.Cells;
    using Microsoft.EntityFrameworkCore;
    using System.Reflection;
    
    namespace Infrastructure.Data
    {
        public class BookDesinerContext : DbContext
        {
            public BookDesinerContext(DbContextOptions<BookDesinerContext> options) : base(options)
            { 
            }
    
            public DbSet<Book> Books { get; set; }
            public DbSet<Chapter> Chapters { get; set; }
            public DbSet<Page> Pages { get; set; }
            public DbSet<Cell> Cells { get; set; }
    
    
            protected override void OnModelCreating(ModelBuilder builder)
            {
                base.OnModelCreating(builder);
                builder.Entity<Cell>()
                    .HasDiscriminator<string>("cell_type")
                    .HasValue<Cell>("cell")
                    .HasValue<ImageCell>("image_cell")
                    .HasValue<TextCell>("text_cell");
                builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
            }
        }
    }
    

    DbContextSeed:

    using Core.Entities;
    using Core.Entities.BookAggregate;
    using Core.Entities.Cells;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Logging;
    
    namespace Infrastructure.Data
    {
        public class BookDesignerContextSeed
        {
            public static async Task SeedAsync(BookDesinerContext bookDesignerContext,
                ILogger logger,
                int retry = 0)
            {
                var retryForAvailability = retry;
                try
                {
                    if (bookDesignerContext.Database.IsSqlServer())
                    {
                        bookDesignerContext.Database.Migrate();
                    }
    
                    if (!await bookDesignerContext.Books.AnyAsync())
                    {
                        await bookDesignerContext.Books.AddRangeAsync(
                            GetPreconfiguredBooks());
    
                        await bookDesignerContext.SaveChangesAsync();
                    }
                }
                catch (Exception ex)
                {
                    if (retryForAvailability >= 10) throw;
    
                    retryForAvailability++;
    
                    logger.LogError(ex.Message);
                    await SeedAsync(bookDesignerContext, logger, retryForAvailability);
                    throw;
                }
            }
    
            static IEnumerable<Book> GetPreconfiguredBooks()
            {
                var chapters = GetPreconfiguredChapters().ToList();
                Console.WriteLine(chapters.Count);
                Book borja = new Book();
                borja.Title = "Borja On Fleek 🔥";
                borja.Chapters = chapters;
    
                return new List<Book>
                {
                    borja
                };
            }
    
            static IEnumerable<Chapter> GetPreconfiguredChapters()
            {
                List<Page> pages = GetPreconfiguredPages().ToList();
    
                Chapter chapter1 = new Chapter();
                chapter1.Title = "De Borja bin ig";
                chapter1.Pages = pages.Skip(0).Take(4).ToList();
    
                Chapter chapter2 = new Chapter();
                chapter2.Title = "De Tintefisch Homie joined em Advänture";
                chapter1.Pages = pages.Skip(5).Take(2).ToList();
    
                return new List<Chapter>
                {
                    chapter1, chapter2
                };
            }
    
            static IEnumerable<Page> GetPreconfiguredPages()
            {
                Cell[] cells = GetPreconfiguredCells().ToArray();
                Console.WriteLine(cells);
    
                // Chapter 1
                Page page1 = new Page();
                page1.Cols = 3;
                page1.Rows = 1;
                page1.Cells = new List<Cell> 
                { 
                    cells[0], cells[1]
                };
    
                Page page2 = new Page();
                page2.Cols = 3;
                page2.Rows = 1;
                page2.Cells = new List<Cell>
                {
                    cells[2], cells[3]
                };
    
                ...
    
    
                return new List<Page>
                {
                    page1, page2, page3, page4, page5, page6, page7
                };
    
    
            }
        }
    }
    

    程序反恐精英:

    using Core.Interfaces;
    using Infrastructure.Data;
    using Infrastructure.Logging;
    using Microsoft.EntityFrameworkCore;
    using Core.Services;
    
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Logging.AddConsole();
    
    Infrastructure.Dependencies.ConfigureServices(builder.Configuration, builder.Services);
    
    
    builder.Services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
    builder.Services.AddScoped(typeof(IReadRepository<>), typeof(EfRepository<>));
    builder.Services.AddScoped<IBookService, BookService>();
    builder.Services.AddScoped(typeof(IAppLogger<>), typeof(LoggerAdapter<>));
    builder.Services.AddDbContext<BookDesinerContext>(options => options.UseInMemoryDatabase(databaseName: "Books"));
    
    builder.Services.AddMemoryCache();
    
    builder.Services.AddControllers();
    
    var app = builder.Build();
    
    app.Logger.LogInformation("PublicApi App created...");
    
    app.Logger.LogInformation("Seeding Database...");
    
    using(var scope = app.Services.CreateScope())
    { 
       var scopedProvider = scope.ServiceProvider;
       var context = scopedProvider.GetRequiredService<BookDesinerContext>();
    
        var books = context.Books
            .Include(book => book.Chapters)
            .ThenInclude(chapter => chapter.Pages)
            .ThenInclude(page => page.Cells)
            .ToList();
    }
    
    using (var scope = app.Services.CreateScope())
    {
        var scopedProvider = scope.ServiceProvider;
        try
        {
            var bookDesinerContext = scopedProvider.GetRequiredService<BookDesinerContext>();
            await BookDesignerContextSeed.SeedAsync(bookDesinerContext, app.Logger);
        }
        catch (Exception ex)
        {
            app.Logger.LogError(ex, "An error occurred seeding the DB.");
        }
    }
    
    if (app.Environment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    
    app.UseHttpsRedirection();
    
    app.UseRouting();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
    
    app.Logger.LogInformation("LAUNCHING PublicApi");
    app.Run();
    

    我知道 var chapters = GetPreconfiguredChapters().ToList(); 包含检查时的正确值。为什么会这样 null 调用API时?

    0 回复  |  直到 2 年前