上一篇文章我们讲解了如何用 Fluent API 来配置/映射属性和类型,本文将把重点放在其是如何配置关系的。

  文中所使用代码如下

public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public DateTime EnrollmentDate { get; set; }

        // Navigation properties
        public virtual Address Address { get; set; }
        public virtual OtherInfo OtherInfo { get; set; }
        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }

    public class Department
    {
        public Department()
        {
            this.Courses = new HashSet<Course>();
        }
        // Primary key
        public int DepartmentID { get; set; }
        public string Name { get; set; }
        public decimal Budget { get; set; }
        public System.DateTime StartDate { get; set; }
        public int? Administrator { get; set; }

        // Navigation property
        public virtual ICollection<Course> Courses { get; private set; }
    }

    public class Course
    {
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }

        // Foreign key
        public int DepartmentID { get; set; }
        public string DepartmentName { get; set; }

        public int SomeDepartmentID { get; set; }

        // Navigation properties
        public virtual Department Department { get; set; }
        public virtual ICollection<Enrollment> Enrollments { get; set; }
        public virtual ICollection<Instructor> Instructors { get; set; }
    }

    public class Instructor
    {
        public int InstructorID { get; set; }
        public string Name { get; set; }
        public DateTime HireDate { get; set; }

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

    public class Enrollment
    {
        public int EnrollmentID { get; set; }
        public int CourseID { get; set; }
        public int StudentID { get; set; }

        // Navigation property
        public virtual Course Course { get; set; }
        public virtual Student Student { get; set; }
    }

    public class Address
    {
        public int AddressId { get; set; }
        public string HomeAddress { get; set; }
        public string LiveAddress { get; set; }

        // Navigation property
        public virtual Student Student { get; set; }
    }

    public class OtherInfo
    {
        public int Id { get; set; }
        public string HomeAddress { get; set; }
        public string MailAddress { get; set; }
        public string PhoneNumber { get; set; }
        public string StudentID { get; set; }

        // Navigation property
        public virtual Student Student { get; set; }
    }
View Code

相关文章:

  • 2022-12-23
  • 2021-07-18
  • 2022-01-28
  • 2022-03-05
  • 2021-08-05
  • 2021-07-24
猜你喜欢
  • 2022-01-07
  • 2021-06-18
  • 2021-09-17
  • 2021-11-22
  • 2021-08-24
相关资源
相似解决方案