.NET Core中一对多关系的数据播种

时间:2018-08-03 18:06:41

标签: c# .net entity-framework-core

我正在尝试为具有以下架构的新数据库播种数据:

public class Meeting {

    [Key]
    public string Code { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public DateTime BeginDate { get; set; }
    public DateTime EndDate { get; set; }
    public bool IsArchived { get; set; }
    public List<File> Files {get; set; }
}

public class File : IWistiaMiddlewareModel
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int Id { get; set; }
    public bool IsArchived { get; set; }
    public string FileName { get; set; }
    public string Location { get; set; }
    public int Size { get; set; }
    public int Duration { get; set; }
    public string Extension { get; set; }
    public Media WistiaMedia { get; set; }
    public Meeting Meeting { get; set; }
    public bool Uploaded { get; set; }
}

我只是试图将一些会议和文件数据添加到数据库中,以便可以使用一些测试数据。这是我尝试播入上下文文件的尝试:

protected override void OnModelCreating(ModelBuilder builder)
{

    var testMeeting = new Meeting()
    {
        BeginDate = DateTime.Now,
        EndDate = DateTime.Now,
        Code = "000-2042",
        Description = "A Test meeting to test with",
        IsArchived = false,
        Title = "Test Meeting 1",
        Files = new List<File>()
    };

    var testFile = new File()
    {
        FileName = "The Most Satisfying Video In The World",
        Extension = ".mp4",
        Duration = 259,
        Location = "C:\\Users\\ngoodman\\Downloads",
        Size = 47322483,
        Uploaded = true,
        WistiaMedia = null,
        IsArchived = false,
        Id = 1,
        Meeting = testMeeting
    };

    testMeeting.Files.Add(testFile);

    builder.Entity<Meeting>().HasData(testMeeting);

    builder.Entity<File>().HasData(testFile);
}

当我尝试添加此迁移时,出现以下错误:

  

无法添加实体类型“文件”的种子实体,因为它设置了导航“会议”。要播种关系,您需要将相关实体种子添加到“会议”并指定外键值{'MeetingCode'}。考虑使用'DbContextOptionsBuilder.EnableSensitiveDataLogging'查看所涉及的属性值。

当我在没有种子数据的情况下运行迁移时,它会按预期工作。它也将与会议种子数据一起运行,但是当我包含文件种子代码时,它会爆炸。

我看到它抱怨找不到 MeetingCode 的值,该值是 File 表上的主键。尽管迁移确实在生成的 File 表中添加了“ MeetingCode”字段,但由于它不是 File 模型的实际值,因此我无法设置该值。我的假设是,当我将会议分配给文件时,这应该在幕后发生,但是显然这没有发生吗?

有人可以告诉我们这里出了什么问题吗?如何成功地为File表或任何一对多关系添加种子数据?

0 个答案:

没有答案