【问题标题】:ASP. NET Core 2.2 EF - Database Not SeedingASP。 NET Core 2.2 EF - 数据库未播种
【发布时间】:2019-01-25 09:15:11
【问题描述】:

我正在使用 Asp .Net Core 2.2 和 EntityFramework 开发 MVC Web 应用程序。我对框架很陌生,我正在尝试为数据库播种,但在测试时,数据库仍然是空的。我已经查看了关于通过 Program.cs 调用我的 Initialize 方法的先前帖子,我试图实现这些帖子,所以我不确定我错过了什么? 我试图找到可能发生的事情的答案,但其他解决方案指向框架的早期版本。

任何帮助将不胜感激!

我的数据库初始化方法如下:

public static void Initialize(ApplicationDbContext context)
    {
        {
            //Look for any IncidentTypes
            if (context.IncidentType.Any())
            {
                return; // DB has been seeded
            }

            var incidentTypes = new IncidentType[]
            {
                 new IncidentType { Id = 1, Type = "Urgent"},
                 new IncidentType { Id = 2,Type = "Non-Urgent"}
            };

            foreach (IncidentType t in incidentTypes)
            {
                context.IncidentType.Add(t);
            }
            context.SaveChanges();

            var outcomes = new Outcome[]
            {
                new Outcome { Id = 1, OutcomeText = "This type of incident does not apply"},
                new Outcome { Id = 2, OutcomeText = "Go to ED"},
                new Outcome { Id = 3, OutcomeText = "Go to ED"},
                new Outcome { Id = 4, OutcomeText = "CLEAR & LEAVE"}
            };

            foreach (Outcome o in outcomes)
            {
                context.Outcome.Add(o);
            }
            context.SaveChanges();

            var stages = new Stage[]
            {
                new Stage { Id = 1, OutcomeId = 1, StageName = "Complete PS"},
                new Stage { Id = 2, OutcomeId = 2, StageName = "Do Any Apply?"},
                new Stage { Id = 3, OutcomeId = 3, StageName = "Do Any Apply?"},
                new Stage { Id = 4, OutcomeId = 4, StageName = "Do Any Apply?"}
            };

            foreach (Stage s in stages)
            {
                context.Stage.Add(s);
            }
            context.SaveChanges();

            var stageConditions = new StageCondition[]
            {
                new StageCondition { Id = 1, IncidentTypeId = 1, StageId = 1,
                    ConditionText = "This process does not apply to the following: INSERT"},
                new StageCondition { Id = 2, IncidentTypeId = 1, StageId = 2,
                    ConditionText = "First set of Questions"},
                new StageCondition { Id = 3, IncidentTypeId = 1, StageId = 3,
                    ConditionText = "Second set of Questions"},
                new StageCondition { Id = 4, IncidentTypeId = 1, StageId = 4,
                    ConditionText = "Is there a suitable ED alternative?"},
                new StageCondition { Id = 5, IncidentTypeId = 2, StageId = 1,
                    ConditionText = "This process does not apply to the following: INSERT"},
                new StageCondition { Id = 6, IncidentTypeId = 2, StageId = 2,
                    ConditionText = "First set of Questions"},
                new StageCondition { Id = 7, IncidentTypeId = 2, StageId = 3,
                    ConditionText = "Second set of Questions"},
                new StageCondition { Id = 8, IncidentTypeId = 2, StageId = 4,
                    ConditionText = "Is there a suitable ED alternative?"}
            };

            foreach (StageCondition c in stageConditions)
            {
                context.StageCondition.Add(c);
            }
            context.SaveChanges();
        }

我的 Program.cs 类如下:

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;

            try
            {
                var context = services.GetRequiredService<ApplicationDbContext>();
                DbInitializer.Initialize(context);
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occured creating the DB.");
            }
        }

        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

我的数据库上下文如下:

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
    public DbSet<Models.IncidentType> IncidentType { get; set; }
    public DbSet<Models.Incident> Incident { get; set; }
    public DbSet<Models.StageCondition> StageCondition { get; set; }
    public DbSet<Models.Outcome> Outcome { get; set; }
    public DbSet<Models.Stage> Stage { get; set; }
}

编辑: 在下方添加了 IncidentType 模型:

    public class IncidentType
{
    public int Id { get; set; }
    public string Type { get; set; }
}

}

【问题讨论】:

  • 你好琼斯。您能否添加 IncidentType 模型? ID是[键]吗?在这种情况下,您无法插入具有给定“Id”的值,因为 IDENTITY_INSERT 已打开。此外,如果这是正常的整数字段,请检查表 IncidentType 是否由于第一个 if 条件而被播种。
  • 嗨。我添加了 IncidentType 模型。我试过删除第一个 If 语句来检查但没有运气。
  • 按照约定,一个名为 Id 或 Id 的属性将被配置为实体的键。重命名您的 Id 字段或从播种机中删除 Id 初始化。这应该会有所帮助。
  • 我从播种机中删除了 ID,它现在可以工作了!感谢您的帮助

标签: c# entity-framework web-applications asp.net-core-2.2


【解决方案1】:

由于 IDENTITY_INSERT 默认开启,您的项目失败。按照惯例,实体框架将 Id /Id 视为主键,并且无法插入具有给定“Id”的记录。如果您不想将其视为主键,请重命名此字段,但我建议保持原样并允许它工作。

此外,我建议阅读有关依赖注入和将 DatabaseSeeder 作为单例注入的信息,以便在应用程序启动后创建一个实例。在 Program 类中插入任何类型的逻辑都是不好的做法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    相关资源
    最近更新 更多