I have the following models:
public class Device
{
[Key]
public int ID { get; set; }
public int? SimCardID{ get; set; }
[ForeignKey("SimCardID")]
public virtual SimCard { get; set; }
[DataType(DataType.Text)]
[Required]
[MaxLength(16)]
public string Imei { get; set; }
[DataType(DataType.Text)]
[Required]
[MaxLength(20)]
public string Name { get; set; }
}
public class SimCard
{
[Key]
public int ID { get; set; }
[DataType(DataType.PhoneNumber)]
[Required]
[MaxLength(20)]
public string PhoneNumber { get; set; }
[DataType(DataType.Text)]
[Required]
[MaxLength(40)]
public string SerialNumber { get; set; }
[DataType(DataType.Text)]
[Required]
[MaxLength(20)]
public string Provider { get; set; }
}
One Device (1) has at the most one (c) sim card. Relationship is therefore 1:c. How can I implement that in EF Code First?
This relation cannot be mapped with EF and it even doesn’t work in the database.
You say that SIM cart can exists without device. That is ok but you also say that Device can exist without SIM card and you still want referential integrity and one-to-one relation. What does it mean?
It means that Device table must have:
First problem is in the database. If you place unique index to nullable column you will get some surprised result – null is considered as value and only single record can have null assigned otherwise it will violate unique constraint => that means you can have only one device without sim card.
Second problem is in the EF. EF doesn’t support unique keys so it doesn’t see that one-to-one relation (and it will not create index for you). The only possibility to use real one-to-one relation in EF is to place FK on device’s PK = device will have same PK value as a SIM but in this scenario you cannot have device without SIM card.