繁体   English   中英

配置单向一对多关系EF6

[英]Configure unidirectional one to many relationship EF6

我有两个实体,如下所示:

public class FirstEntity
{
    public int Id { get; set; }

    public ICollection<SecondEntity> SecondEntityCollection { get; set; }
}

public class SecondEntity
{
    [Key]
    [Column(Order = 0)]
    public int FirstEntitySomeId { get; set; }

    [Key]
    [Column(Order = 1)]
    public int SecondEntityId { get; set; }
}

我想生成一个迁移,以使用SecondEntitySecondEntity添加到数据库。 问题在于EF生成的迁移如下:

CreateTable("dbo.SecondEntity",
        c => new
        {
            SecondEntityId = c.Int(nullable: false),
            FirstEntitySomeId = c.Int(nullable: false),
            FirstEntity_Id = c.Int(),
        })
        .PrimaryKey(t => new {t.SecondEntityId, t.FirstEntitySomeId})
        .ForeignKey("dbo.FirstEntity", t => t.FirstEntity_Id)
        .Index(t => t.FirstEntity_Id);

由于FirstEntitySomeId不遵循约定(我想以这种方式保留名称),因此它会自动生成一个新列FirstEntity_Id作为外键。

如何强制EF不生成新列,而是将FirstEntitySomeId用作FK? 请注意,该关系是单向的。 SecondEntity不包含FirstEntity类型的导航属性(并且不应该)。

使用流畅的映射,您可以执行以下操作:

modelBuilder.Entity<FirstEntity>()
    .HasMany(m => m.SecondEntityCollection)
    .WithRequired()
    .HasForeignKey(m => m.FirstEntitySomeId);

如果使用属性,则可以通过以下方式设置外键:

public class FirstEntity
{
    public int Id { get; set; }
    [ForeignKey("FirstEntitySomeId")]
    public ICollection<SecondEntity> SecondEntityCollection { get; set; }
}

暂无
暂无

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

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