使用ICollection在模型类中显示外键关系 [英] showing foreign key relationship in model class using ICollection

查看:116
本文介绍了使用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; } 
}

但是我发现将外键类定义为ICollection.两种声明类型有什么区别?我们应该使用哪一个?

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; }

推荐答案

您应该使用哪种关系取决于您是否需要1:1关系或1:n关系.

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

由于每个AppointmentModel都有一个VisitorId,因此每个AppointmentModel都会有一个Visitor(否).因此,navigationproperty是一个实例,没有任何集合.

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.

这篇关于使用ICollection在模型类中显示外键关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆