简体   繁体   English

实体框架列表将所有属性返回到映射模型

[英]Entity Framework list return all properties to mapped models

I have three classes: Students, Subjects and Grades. 我有三个班级:学生,科目和年级。

public class Grades
{
    [Key]
    public int Id { get; set; }
    public Student Student { get; set; }
    public Subject Subject { get; set; }
    public int Year { get; set; }
    public string Grade { get; set; }
}

Student Class 学生班

 public class Student
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string Nationality { get; set; }
    }

Subject Class 学科课

public class Subject
{
    [Key]
    public int Id { get; set; }
    public string Title { get; set; }
}

I want to return all Grades but with properties of Student and Subject expanded, like I can access Grade.Name 我想返回所有成绩,但是扩展了Student和Subject的属性,例如我可以访问Grade.Name

Grade.Gender 年级,性别

Grade.Nationality 年级,国籍

Grade.Year 年级

Grade.Grade 年级

instead of Grade.Student.Name 而不是Grade.Student.Name

Grade.Student.Gender 年级,学生,性别

Grade.Student.Nationality 年级,学生,国籍

Use these expressions to expand your data. 使用这些表达式扩展数据。 Note that they will not be of the Grade class but they will be anonymous class with properties you want. 请注意,它们将不是Grade类,但将是具有所需属性的匿名类。 If you need to pass these items to other methods, you have to create explicit class that has these properties. 如果需要将这些项目传递给其他方法,则必须创建具有这些属性的显式类。 Otherwise you may access them directly in the same method. 否则,您可以使用相同的方法直接访问它们。 Like, expandedGrades.First().Name . 就像expandedGrades.First().Name

var expandedGrades =
    DBContext.Grades.Select(grade =>
    new
    {
        Name = grade.Student.Name,
        Gender = grade.Student.Gender,
        Nationality = grade.Student.Nationality,
        Year = grade.Year,
        Grade = grade.Grade
    });

or 要么

var expandedGrades =
                from grade in DBContext.Grades
                select new
                {
                    Name = grade.Student.Name,
                    Gender = grade.Student.Gender,
                    Nationality = grade.Student.Nationality,
                    Year = grade.Year,
                    Grade = grade.Grade
                };

Assuming you have proper relationships set between your Students, Subjects and Grades tables. 假设您在“学生”,“科目”和“成绩”表之间设置了适当的关系。 In Entity framework you can use .include to get your job done. 在实体框架中,您可以使用.include来完成工作。

A basic example: 一个基本的例子:

Blog blogs = context.Blogs 
                    .Include(b => b.Posts) 
                    .ToList(); 

with this now you can use blogs.Posts directly. 现在,您可以直接使用blogs.Posts

Reference : https://msdn.microsoft.com/en-in/data/jj574232.aspx 参考: https : //msdn.microsoft.com/zh-cn/data/jj574232.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM