It’s very simple to create a one-to-many relationship between entities in Code First model. Just place ICollection<T2> at “one” end of the relationship, and T1 at the “many” end.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
[Table("Clients", Schema = "dbo")] public class Client { [Key] public int Id { get; set; } public string Name { get; set; } public ICollection<Phone> Phone { get; set; } } [Table("Phones", Schema = "dbo")] public class Phone { [Key] public int Id { get; set; } public string Number { get; set; } public virtual Client Client { get; set; } } |
The result is shown in the following diagram. EF creates new field for the foreign key, the name is autogenerated in the form Entity_Key (in my case, Client_Id).
In order to convert this relationship to one-to-one (yeah, Entity Framework allows you to do this), it seems that it’s enough to change ICollection to Phone. But EF throws an error:
Unable to determine the principal end of an association between the types 'Clients.Phone' and 'Clients.Client'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
It means you need to explicitly mark one end of the relationship as Required attribute.
1 2 |
[Required] public virtual Client Client { get; set; } |
But EF won’t create a field for foreign key, it uses the primary key of Phone entity to be the foreign key too.
The same action can be achieved by adding ForeignKey attribute before primary key field instead a Required. So my Phone class will look like this:
1 2 3 4 5 6 7 8 9 10 |
[Table("Phones", Schema = "dbo")] public class Phone { [Key, ForeignKey("Client")] public int Id { get; set; } public string Number { get; set; } public virtual Client Client { get; set; } } |