It’s the second time I’m seeing the following error this week and I thought I should document it:
B_A_Source: Multiplicity is not valid in Role ‘B_A_Source’ in relationship ‘B_A’. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be ‘*’.
I got the above error while adding an EF migration for the following models:
1public class A
2{
3 public int Id { get; set; }
4 public string SomeField { get; set; }
5 public virtual B B { get; set; }
6}
7
8public class B
9{
10 public int Id { get; set; }
11 [ForeignKey("A")]
12 public int? AId { get; set; }
13 public virtual A A { get; set; }
14}
In the above example, A and B are in a one-to-many relationship. So the navigation property in A should be udpated to public virtual ICollection<B> Bs { get; set; }.
However what I actually intended to do was have a one to zero-or-one relationship between B and A. So the proper fix would be to make B the parent and A the child. Or in EF terms, make B the principal end and A the dependent end.
1public class B
2{
3 public int Id { get; set; }
4 public virtual A A { get; set; }
5}
6
7public class A
8{
9 [Key, ForeignKey("B")]
10 public int Id { get; set; }
11 public string SomeField { get; set; }
12 public virtual B B { get; set; }
13}
Whenever a one-to-one (or a one to zero-or-one) relationship is desired the dependent end’s foreign key should be its primary key as well.
Oh and BTW, a pure one-to-one relationship doesn’t really exist.
Update Oct 2017: Here’s a related post I wrote this Valentines day: Notes on database relationships.