【问题标题】:defining navigational property in model classes在模型类中定义导航属性
【发布时间】:2021-10-04 20:56:56
【问题描述】:

我在模型课上学习关系。有关表格关系,请参阅附图。 共有三个表,部门、员工、位置。 当为这些表创建模型类时,我对导航属性感到困惑。 员工等级:

public class employee
{
    public employee()
    {
        this.location = new HashSet<location>();
    }
    //attributes
    
    public virutal department department {get;set}
    public virtual ICollection<location> locations {get;set}
}

然后在部门类:

public class department
{
    //attributes
    public virutal ICollection<employee> employees {get;set}
}

在位置类中:

public class location
{
    public virutal employee employee {get;set}
}

为什么在employee 类中department 被定义为virutal department department 而location 被定义为virtual ICollection&lt;location&gt; locations。为什么只对定位使用ICollection?

在department 模型中,employee 类定义为virutal ICollection&lt;employee&gt; employees,但在location 模型中,员工定义为virutal employee employee。为什么会这样,请澄清。

同样在employee类中location被定义为HashSet&lt;location&gt;()在constructor中,为什么会这样定义呢?这个导航属性让我在项目中继续前进感到困惑。请让我澄清一下。谢谢!!!

【问题讨论】:

    标签: asp.net asp.net-mvc entity-framework asp.net-mvc-4 navigational-properties


    【解决方案1】:

    根据你分享的这个逻辑,它说

    一名员工可以隶属于一个部门,但可以隶属于多个位置。这称为一对多关系

    一个部门可以有多个员工 一个位置可以有一个员工。 所以这意味着一名员工可以在多个地点工作,但地点只能有一名员工 这也是一对多。

    HashSet 是 C# 中的键值对数据类型。它类似于 JavaScript 中的对象;

    ICollection 是一个通用接口。它需要一个类型,并且可以在内部保存多个值,就像 List 类型一样。但它没有添加、清除或包含等方法。为了拥有这些方法,您应该实现 IList 接口。

    员工的构造函数在每次初始化时都会初始化一个位置哈希集。这意味着您初始化附加到它的位置的哈希集。 (意味着在每个实例上,只需调用类对象)

    并且属性前面的虚拟关键字会导致“延迟加载”

    lazy loading ef

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      相关资源
      最近更新 更多