【问题标题】:Entity Framework Code First: 1:0..1 Change Foreign Key Location实体框架代码优先:1:0..1 更改外键位置
【发布时间】:2016-04-20 11:22:33
【问题描述】:

我在实体框架代码优先模型中定义了一个 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 表中创建的。这使得批量插入新邮票变得困难/缓慢,就像你总是需要更改Album 表并在那里更新StampId 外键。 (这意味着我需要更改跟踪来更改这些字段)

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

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

【问题讨论】:

    标签: c# mysql entity-framework ef-code-first foreign-key-relationship


    【解决方案1】:

    好的,我用我在这里找到的很好的例子来解决这个问题:http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

    诀窍是使用“Stamps”表中的“AlbumID”外键作为主键。这意味着 Stamp Id 将不是主键,并且主键对于不存在的 ID 将具有“间隙”。所以换句话说,通过这样做,您可以保证一张专辑只有一个邮票。 由于这个概念有点烦人,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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 2012-05-10
      • 2015-02-24
      • 2021-01-05
      • 2011-08-05
      相关资源
      最近更新 更多