How do I create a primary key using two foreign keys in Entity Framework 5 code?
I have an object where the primary key consists of two foreign keys for two other tables. I have a config working with the following, but the table is created with two FK links.
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 created 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 DB correctly, but I think EF requires correct navigation properties? What's the correct way to get the correct database schema?
+3
Supergibbs
source
to share
1 answer
I understood that! Add HasMany to the config of third party objects:
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);
}
+2
Supergibbs
source
to share