0

I seem to be having trouble with database first multiplicity within the design. I am using EF v5.0

I have two db entities with the following (psuedo classes for example):

entity {
    long Id; //PK
    bool myProp;
}

entity_detail {
    long entityID; //FK to entity.Id
    string name;
    datetime entered;
}

When I update the model from the database it correctly generates these classes in the .tt, however, it puts the entity_detail into an ICollection<entity_detail> in the entity class.

This is due to the multiplicity, when I change the multiplicity from Many (*) to Zero or One (0..1) within the EDMX, it will error out and force me to use Many (*)

The issue with this scenario is that the entity_detail should ONLY be generated if myProp is set to false (to avoid redundant data in db)

Thus being a 0..1, any idea on how to set this up from the database perspective to get the EDMX to update it to 0..1 on the entity end and 1 on the entity_detail end?

Thanks in advance!

IntricateJake
  • 105
  • 10
  • A 0..1 relationship would involve a nullable entity detail ID inside entity. – Steve Py Nov 08 '18 at 23:37
  • @StevePy Why would you need an entity_detail entity at all if it is not required by the dependent? For example in codefirst you are able to do modelBuilder.Entity().HasOptional(e => e.entity_detail).WithRequired(e => e.entity); – IntricateJake Nov 09 '18 at 16:00
  • Yes, and that should result in a nullable child ID and associated navigation property in the parent entity. The nullable FK means this parent either has 1 child, or 0 child. A collection would be HasMany().WithRequired() and EF allows 0 or many children. (any attempt to limit it to 0..1 has to be done in code.) A DB FK controlled by the child forms 1-many, there's no way to restrict that no two children can refer to the same parent. – Steve Py Nov 10 '18 at 05:48

1 Answers1

0

For anyone looking for the answer, the correct setup was to make the foreign key (entityID) column on the entity_detail object also a primary key.

This way it would be unique but only be required if it exists (0..1)

Hope this helps!

IntricateJake
  • 105
  • 10