nischalinn
nischalinn

Reputation: 1175

showing foreign key relationship in model class using ICollection

I have a model class which has foreign key relationship,

public class AppointmentModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int AppointmentId { get; set; }
    [Required]
    public string AppointmentTime { get; set; }
    [Required]
    public int AppointmentRoom { get; set; }            
    
    [ForeignKey("VisitorId")]
    public VisitorModel Visitors { get; set; } 
    public int VisitorId { get; set; }  
}

public class VisitorModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int VisitorId { get; set; }
    [Required]
    public string VisitorName { get; set; }
    public int VisitorAddr { get; set; } 
}

But I have found defining foreign key class as ICollection. What is the difference in both the declaration types? Which one should we use?

[ForeignKey("VisitorId")]
public ICollection<VisitorModel> Visitors { get; set; }

Upvotes: 0

Views: 145

Answers (1)

monty
monty

Reputation: 8755

Which one you should use depends if you need a 1:1 relationship or a 1:n relationship.

Since each AppointmentModel has one VisitorId there will be one Visitor(no s) per AppointmentModel. So the navigationproperty is a single instance and no collection.

Upvotes: 1

Related Questions