代码首次迁移添加一对多关系

时间:2014-08-05 12:22:35

标签: entity-framework one-to-many code-first ef-migrations

我目前有一台服务器"实体,定义如下:

public class EntityServer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

我想添加一个新的"主机"实体,定义如下:

public class EntityHost
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string PublicIP { get; set; }

    private ICollection<EntityServer> _servers;
    public virtual ICollection<EntityServer> Servers
    {
        get { return _servers ?? (_servers = new HashSet<EntityServer>()); }
        set { _servers = value; }
    }
}

所以我添加了

public virtual EntityHost Host { get; set; }

到我的服务器实体,将这些实体与一对多关系链接

modelBuilder.Entity<EntityHost>()
  .HasMany<EntityServer>(x => x.Servers)
  .WithRequired(x => x.Host);

并按顺序产生了迁移:

public partial class MultiHosts : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.EntityHosts",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Name = c.String(),
                    PublicIP = c.String(),
                })
            .PrimaryKey(t => t.Id);

        AddColumn("dbo.EntityServers", "Host_Id", c => c.Int(nullable: false));
        CreateIndex("dbo.EntityServers", "Host_Id");
        AddForeignKey("dbo.EntityServers", "Host_Id", "dbo.EntityHosts", "Id", cascadeDelete: true);
    }

    public override void Down()
    {
        DropForeignKey("dbo.EntityServers", "Host_Id", "dbo.EntityHosts");
        DropIndex("dbo.EntityServers", new[] { "Host_Id" });
        DropColumn("dbo.EntityServers", "Host_Id");
        DropTable("dbo.EntityHosts");
    }
}

当我尝试访问上下文时(我理解为服根据模型的要求链接到主机,因为hosts表是空的,我因为FK违规而无法访问主机实体以添加一个....)

所以,我的问题是:如何为存在服务器插入默认主机?

1 个答案:

答案 0 :(得分:1)

作为一种技巧,您可以先将Server设置为Optional

modelBuilder.Entity<EntityHost>()
  .HasOptional(x=>x.Server)
  .WitMany(x => x.Hosts);

运行

Add-Migrations set_server_optional
update-Database

更新您的数据库,然后将Server更改为Required

modelBuilder.Entity<EntityHost>()
  .HasRequired(x=>x.Server)
  .WithMany(x => x.Hosts);

最后

Add-Migrations set_server_required
update-Database