Supergibbs
Supergibbs

Reputation: 1470

How do I create a primary key using two foreign keys in Entity Framework 5 code first?

I have an entity where the primary key consists of two foreign keys to two other tables. I have the configuration working with the following but the table is generated with two FK references.

The table:

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)

is generated from:

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);
}

If I comment out the line

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

on Entity2 and Entity3 then it generates the DB correctly but I think EF requires the navigational properties right? What is the correct way to get the proper database schema?

Upvotes: 3

Views: 822

Answers (1)

Supergibbs
Supergibbs

Reputation: 1470

I figured it out! Add this HasMany to the foreign entity configs:

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);
}

Upvotes: 2

Related Questions