簡體   English   中英

EF6 代碼優先:使用自參考數據播種

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

目標
在我的表中有一個根記錄,它將自己引用為它的父級。

背景信息
我通常使用 EF Core,所以一切都很簡單,使用

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

但是我似乎無法讓它與 EF6 Code First 一起使用。 不幸的是,我無法遷移到 EF Core,因為該項目面向 .NET Framework 4.8(我無法更改)。
不幸的是,下面提供的代碼無法像我希望的那樣工作。

模型

[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; }
}

數據庫上下文

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());
    }
}

初始化程序

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);
    }
}

正如@Damien_The_Unbeliever 和@BradleyUffner 所評論的那樣,讓對象引用本身表明它是根對象實際上並不是合適的方式。

將父元素設置為null作為根元素的指示是眾所周知的模式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM