3

我有一个实体,其中主键由指向其他两个表的两个外键组成。我有使用以下配置的配置,但该表是使用两个 FK 引用生成的。

桌子:

domain.Entity1
    MorePK (PK, FK, int, not null)
    Entity2_Id (PK, FK, int, not null)
    Entity3_Id (PK, FK, int, not null)
    OtherData (varchar, null)
    Entity2_Id1 (FK, int, null)
    Entity3_Id1 (FK, int, null)

生成自:

public Entity1
{
    public int MorePK { get; set; }
    public int Entity2_Id { get; set; }
    public int Entity3_Id { get; set; }

    public string OtherData { get; set; }

    public virtual Entity2 Entity2 { get; set; }
    public virtual Entity3 Entity3 { get; set; }
}

public Entity2
{
    public int Id { get; set; }
    public virtual List<Entity1> Entity1s { get; set; }
}

public Entity3
{
    public int Id { get; set; }
    public virtual List<Entity1> Entity1s { get; set; }
}

public class Entity1Config : EntityTypeConfiguration<Entity1>
{
    HasKey(k => new { k.MorePK, k.Entity2_Id, k.Entity3_Id });

    HasRequired(p => p.Entity2)
        .WithMany()
        .HasForeignKey(p => p.Entity2_Id);

    HasRequired(p => p.Entity3)
        .WithMany()
        .HasForeignKey(p => p.Entity3_Id);

    Property(x => x.Entity2_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    Property(x => x.Entity3_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}

如果我注释掉该行

public virtual List<Entity1> Entity1s { get; set; }

在 Entity2 和 Entity3 上,它会正确生成数据库,但我认为 EF 需要导航属性,对吗?获取正确的数据库模式的正确方法是什么?

4

1 回答 1

2

我想到了!将此 HasMany 添加到外部实体配置中:

public Entity2Config : EntityTypeConfiguration<Entity2>
{
    HasMany(x => x.Entity1s)
        .WithRequired(x => x.Entity2)
        .HasForeignKey(x => x.Entity2_Id);
}

public Entity3Config : EntityTypeConfiguration<Entity3>
{
    HasMany(x => x.Entity1s)
        .WithRequired(x => x.Entity3)
        .HasForeignKey(x => x.Entity3_Id);
}
于 2013-02-01T02:08:49.937 回答