Entity Framework 代码优先:1:0..1 更改外键位置

Entity Framework Code First: 1:0..1 Change Foreign Key Location

我在 Entity Framework 代码优先模型中定义了一个 1 对 0..1 关系,如下所示:

public class Album
{
    public int AlbumId { get; set; }

    public int StampId { get; set; }

    public Stamp Stamp { get; set; }

    // other properties
}

public class Stamp
{
    public int StampId { get; set; }

    public int AlbumId { get; set; }

    [Required]
    public Album Album { get; set; }

    // other properties
}

所以..一张专辑有 0..1 个邮票,一张邮票总是只有一张专辑。我这里的配置很好用。但是,当我查看数据库中生成的列时,我有点不高兴:外键是在 Album table.. 中创建的,这使它成为 hard/slow批量插入新邮票,因为您总是需要更改 Album table 并在那里更新 StampId 外键。 (这意味着我需要更改跟踪来更改这些字段)

如何告诉 Entity Framework 在 Stamp table 中创建外键?

我也不确定导航属性的声明在这种情况下扮演什么角色。是否在两个方向上都定义了这些属性重要吗?

好的,我用我在这里找到的很好的例子想通了:http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

诀窍是使用'Stamps'table中的'AlbumID'外键作为主键。因此,这意味着 Stamp ID 将不是主键,并且对于不存在的 ID,主键将具有 'gaps'。所以换句话说,这样做可以保证一张专辑 只有一个 印章。 因为这个概念有点烦人,所以 one can still simulate 一个 UID 'StampID' 每当你添加一个新条目时它都会递增。

所以在我的例子中是:

public class Album
{
    public int AlbumId { get; set; }

    public Stamp Stamp { get; set; }

    // other properties
}

public class Stamp
{
    [Index(IsUnique = true)] // another UID, just to follow the naming pattern        
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int StampId { get; set; }

    [Key, ForeignKey("Album")] // The PK, taken as FK from the associated Album
    public int AlbumId { get; set; }

    [Required] // the required attribute just makes validation errors more readable
    public Album Album { get; set; }

    // other properties
}