I have three entities:
public class MainEntity()
{
public long Id { get; set; }
public long EntityAId { get; set; }
public EntityA OptionalEntityA { get; set; }
public long EntityBId { get; set; }
public EntityB OptionalEntityB { get; set; }
public string SProp { get; set; }
}
public class EntityA()
{
public long Id { get; set; }
public long MainEntityId { get; set; }
public MainEntity RequiredEntity { get; set; }
}
public class EntityB()
{
public long Id { get; set; }
public long MainEntityId { get; set; }
public MainEntity RequiredEntity { get; set; }
}
All three entities have there own Id generated by database:
Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
How can I define the Relationship between MainEntity and EntityA and EntityB in order to have:
- MainEntity may have zero or one EntityA
- MainEntity may have zero or one EntityB
- EntityA must have one MainEntity
- EntityB must have one MainEntity
In my MainEntityConfigurationMap I have defined relation like this:
HasOptional(m => m.OptionalEntityA).WithRequired(ea => ea.RequiredEntity);
HasOptional(m => m.OptionalEntityB).WithRequired(eb => eb.RequiredEntity);
Looking at the generated migration I have this for EntityA:
CreateTable(
"dbo.EntityA",
c => new
{
Id = c.Long(nullable: false, identity: true),
MainEntityId = c.Long(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.MainEntity", t => t.Id)
.Index(t => t.Id);
Entity Framework is defining a shared primary key here, is there a way to avoid that and make MainEntityId poiting to MainEntity.Id?