简体   繁体   English

EF-1:1关系不在主键上

[英]EF - 1:1 relation not on primary key

I want to create an optional 1:1 mapping between two existing (legacy) tables where each MainTable record may or may not have - at most - one SubTable record: 我想在两个现有(旧式)表之间创建一个可选的1:1映射,其中每个MainTable记录可能具有或最多不具有一个SubTable记录:

internal class MainTable
{
    [Key]
    public int Id { get; set; }
}
internal class SubTable
{
    [Key]
    public int Id { get; set; }
    public int MainTableId { get; set; }
}

The SubTable.Id does not really serve any purpose but preferably it remains the PrimaryKey and AutoGenerated because of legacy code still running. SubTable.Id并没有任何作用,但由于遗留代码仍在运行,因此最好保留它为PrimaryKey和AutoGenerated。

OnModelCreating gets updated with: OnModelCreating更新为:

modelBuilder.Entity<MainTable>()
    .HasOptional(x => x.Sub)
    .WithRequired(x => x.Main);

With the above Models, I run Add-Migration initial and Update-Database . 使用上述模型,我可以运行Add-Migration initialUpdate-Database I then update the models to: 然后,我将模型更新为:

internal class MainTable
{
    [Key]
    public int Id { get; set; }
    public SubTable Sub { get; set; } // new
}
internal class SubTable
{
    [Key]
    public int Id { get; set; }
    public int MainTableId { get; set; }
    public MainTable Main { get; set; } // new
}

Running Add-Migration creates a new one but running it gives the following error: Table 'dbo.SubTable' doesn't exist 运行Add-Migration会创建一个新的,但运行时会出现以下错误: Table 'dbo.SubTable' doesn't exist

The generated migration: 生成的迁移:

public override void Up()
{
    DropPrimaryKey("dbo.SubTable");
    AlterColumn("dbo.SubTable", "Id", c => c.Int(nullable: false));
    AddPrimaryKey("dbo.SubTable", "Id");
    CreateIndex("dbo.SubTable", "Id");
    AddForeignKey("dbo.SubTable", "Id", "dbo.MainTable", "Id");
}

I'm unsure why EF wants to drop all primary keys etc but the last line seems to suggest that it wants to bind Sub.Id->Main.Id while it should bind Sub.MainTableId->Main.Id. 我不确定为什么EF要删除所有主键等,但是最后一行似乎暗示它想绑定Sub.Id-> Main.Id,而应该绑定Sub.MainTableId-> Main.Id。

After that I've tried messing with DataAnnotationAttributes instead [ForeignKey] , [Index("name", 1, IsUnique = true)] etc but to no avail. 之后,我尝试使用DataAnnotationAttributes代替[ForeignKey][Index("name", 1, IsUnique = true)]等,但无济于事。

Ill do something like this 会做这样的事情

internal class MainTable
{
    [Key]
    public int Id { get; set; }

    public virtual SubTable Sub { get; set; } // new
}
internal class SubTable
{
    [Key]
    public int Id { get; set; }
    public int MainTableId { get; set; }

    [ForeignKey("MainTableId")]
    public virtual MainTable Main { get; set; } // new
}

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

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