实体框架中的构造方法初始化 [英] Constructor Initialization in Entity framework

查看:76
本文介绍了实体框架中的构造方法初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这两个代码之间的区别,无法理解我应该在构造函数中初始化什么:代码1:

I want to know the difference between those two codes can't understand what should I initialize the property in the constructor: Code 1:

public class Student
{
    public Student() 
    {
        this.Courses = new HashSet<Course>();
    }

    public int StudentId { get; set; }
    [Required]
    public string StudentName { get; set; }

    public virtual ICollection<Course> Courses { get; set; }
}

public class Course
{
    public Course()
    {
        this.Students = new HashSet<Student>();
    }

    public int CourseId { get; set; }
    public string CourseName { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

code2:

public class Student
{  
    public int StudentId { get; set; }
    [Required]
    public string StudentName { get; set; }

    public virtual ICollection<Course> Courses { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

谁能帮助我理解这两个代码的不同之处,谢谢

can anyone help me to understand the meaning of the difference for those two codes , thanks

推荐答案

在数据库上下文中使用模型时,避免空引用异常,或者一般而言,最好使用最能表达您意图的集合.如果您不打算专门使用HashSet的独特功能,那么我将不使用它.

Avoiding null reference exception while using the model in DB context, or Generally speaking, it is best to use the collection that best expresses your intentions. If you do not specifically intend to use the HashSet's unique characteristics, I would not use it.

这篇关于实体框架中的构造方法初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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