【问题标题】:Why is there no Seed method to override in my Migration class in C# EF?为什么在 C# EF 的 Migration 类中没有可覆盖的 Seed 方法?
【发布时间】:2018-11-20 05:09:32
【问题描述】:

您好,我在编写此代码时没有找到合适的方法来覆盖

protected override void Seed(MuziekApp.MuziekContext context) { }

为什么我的迁移中没有可覆盖的 Seed 方法?我到底错过了什么或做错了什么?

using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;

namespace MuziekApp.Migrations
{
    public partial class Second : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {

        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {

        }

        protected override void Seed(MuziekApp.MuziekContext context)
        {

            List<Artiest> lijst = new List<Artiest>()
            {
                new Artiest() { ArtiestID = 1, Naam = "Jane", InstrumentID = 1, InstrumentNaam = "Saxofoon", PopgroepID = 1, GroepNaam = "Killers"},
                new Artiest() { ArtiestID = 2, Naam = "Charles", InstrumentID = 2, InstrumentNaam = "Gitaar", PopgroepID = 1, GroepNaam = "Killers"},
                new Artiest() { ArtiestID = 3, Naam = "Miguel", InstrumentID = 1, InstrumentNaam = "Saxofoon", PopgroepID = 2, GroepNaam = "Rock"},
                new Artiest() { ArtiestID = 4, Naam = "John", InstrumentID = 2, InstrumentNaam = "Gitaar", PopgroepID = 2, GroepNaam = "Rock" }
             };

            List<Instrument> lijst2 = new List<Instrument>()
            {
                new Instrument() {  InstrumentID = 1, InstrumentNaam = "Saxofoon"},
                new Instrument() {  InstrumentID = 2, InstrumentNaam = "Gitaar"}
             };

            List<Popgroep> lijst3 = new List<Popgroep>()
            {
                new Popgroep() { PopgroepID = 1, GroepNaam = "Killers"},
                new Popgroep() { PopgroepID = 2, GroepNaam = "Rock"}
             };

            context.Artiesten.AddRange(lijst);
            context.Instrumenten.AddRange(lijst2);
            context.Popgroepen.AddRange(lijst3);
        }
    }
}

【问题讨论】:

  • EF Core 没有种子方法。
  • 根据文档docs.microsoft.com/en-us/ef/core/api/…,看起来Migration 没有Seed 方法
  • 那我在哪里可以使用种子法呢?
  • 在你的迁移中使用 Sql()
  • 您能否提供一个关于如何在迁移中使用 Sql 的示例?

标签: c# entity-framework


【解决方案1】:

您可以在迁移文件中使用 Sql()

Sql("INSERT INTO Artiests (Name, InstrumentID) VALUES ('Jane', 1)");

它只允许您使用 SQL 语句进行播种。您可能希望首先像您的仪器一样播种数据,以便 ID 对您的 FK 有效。只需考虑您放置它们的顺序即可。

【讨论】:

  • 这属于哪个方法
  • 更改将进入Up()。如果您想在降级时进行更改,可以将它们放在Down()
【解决方案2】:

【讨论】:

    猜你喜欢
    • 2017-09-03
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多