简体   繁体   English

EF6 代码优先:使用自参考数据播种

[英]EF6 Code First : Data Seeding with self reference

Goal目标
Having a root record in my table, which references itself as its parent.在我的表中有一个根记录,它将自己引用为它的父级。

Background Info背景信息
I usually work with EF Core, so everything is pretty straight forward using我通常使用 EF Core,所以一切都很简单,使用

modelBuilder.Entity<Type>().HasData(...);

However I can't seem to get it to work with EF6 Code First.但是我似乎无法让它与 EF6 Code First 一起使用。 Unfortunately I cannot migrate to EF Core, since the project is targeting .NET Framework 4.8 (which I am not able to change).不幸的是,我无法迁移到 EF Core,因为该项目面向 .NET Framework 4.8(我无法更改)。
The code provided below unfortunately doesen't work as I was hoping it would.不幸的是,下面提供的代码无法像我希望的那样工作。

Model模型

[Table("PS_CONTAINERS")]
public class PasswordContainer
{
    public int Id { get; set; }
    public DateTime DateCreate { get; set; } = DateTime.Now;
    public DateTime DateModified { get; set; } = DateTime.Now;
    public string CreatedBy { get; set; }
    public string ModifiedBy { get; set; }
    public string DisplayName { get; set; }
    public int? ParentContainerId { get; set; }

    [ForeignKey("ParentContainerId")]
    public PasswordContainer ParentContainer { get; set; }
    public ICollection<PasswordContainer> ChildContainers { get; set; }
}

DbContext数据库上下文

public class SqlDbContext : DbContext
{
    public DbSet<PasswordContainer> Containers { get; set; }
    public DbSet<PasswordEntry> Passwords { get; set; }

    public SqlDbContext(string connectionString) : base(connectionString) {
        Database.SetInitializer(new CobraDbContextInitializer());
    }
}

Initializer初始化程序

public class SqlDbContextInitializer : DropCreateDatabaseIfModelChanges<SqlDbContext>
{
    protected override void Seed(SqlDbContext context)
    {
        // add default container without referencing itself
        var defaultContainer = new PasswordContainer()
        {
            Id = 0,
            DateCreate = DateTime.Now,
            DateModified = DateTime.Now,
            CreatedBy = "System",
            ModifiedBy = "System",
            DisplayName = "System"
        };
        context.Containers.Add(defaultContainer);
        context.SaveChanges();

        // get it again and update it with reference to itself
        var addedContainer = context.Containers.Find(0);
        addedContainer.ParentContainer = addedContainer;
        context.SaveChanges();

        base.Seed(context);
    }
}

As commented by @Damien_The_Unbeliever & @BradleyUffner, having an object reference itself indicating it is the root object is actually not the suitable way.正如@Damien_The_Unbeliever 和@BradleyUffner 所评论的那样,让对象引用本身表明它是根对象实际上并不是合适的方式。

It is a well known pattern to have the parent set to null as indication for the root element.将父元素设置为null作为根元素的指示是众所周知的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM