Linq实体框架:选择没有重复数据的表数据到IEnumerable

时间:2017-11-10 02:32:21

标签: c# asp.net entity-framework linq

我正在使用以下技术:C#,SQL Server,ASP.NET和Entity Framework以及Linq。

我的数据库中有多对多的关系:

my database diagram

模型类:

public class Courses
{
    [Required]
    public int Id { get; set; }
    //more properties here
     public student stud { get; set; }
}

public class inscribe
{
    [Key]
    public intId { get; set; }
    //properties here
    public student student{ get; set; }
    [Required]
    [ForeignKey("student")]
    public string StudentId{ get; set; }
    public Courses Courses{ get; set; }
}

鉴于学生身份,我想返回他/她被列入的课程列表。

这是我到目前为止所尝试的:

public IEnumerable<CursoDto> GetCursosAlumno(Int studentId)
{
     //some code here to validate
     var x = _dbContext
                 .Inscribe.Include(c => c.Courses)
                 .Where(c => c.StudentId == studentId).toList();
     // x variable is a list<inscribe>
}

我的问题是我不知道如何访问课程实体并将其作为列表返回,例如:

var result = X.Courses;
return result; //result is a list<courses>

我该怎么办?如果可能的话,请不要使用foreach块。

由于

2 个答案:

答案 0 :(得分:2)

在Code First方法中,您不需要在模型中添加“链接表”(OP中的inscribe)(它将以透明方式创建)。

//Models
public class Course
{
    [Key]
    public int Id { get; set; }
    //more properties here
     public virtual /*important*/ ICollection<Student> studs { get; set; }
 }
public class Student
{
    [Key]
    public int Id { get; set; }
    //more properties here
     public virtual /*important*/ ICollection<Course> courses { get; set; }
 }

 //Controller
var stud = _dbContext.studs.Where(s => s.Id == /*param*/id).FirstOrDefault();
var courses = stud.courses.ToList();//Real courses with id, name, etc. No Include required

<强>更新
如果你确实需要“链接表”(例如添加一些属性,如sortOrderenrollmentDate),那么模型会有所不同。

//Models
public class Course
{
    [Key]
    public int Id { get; set; }
    //more properties here
     public virtual /*important*/ ICollection<StudentCourse> studs { get; set; }
 }
public class Student
{
    [Key]
    public int Id { get; set; }
    //more properties here
     public virtual /*important*/ ICollection<StudentCourse> courses { get; set; }
 }
[Table("inscribe")]
public class StudentCourse
{
    [Key, Column(Order = 0)]
    public int StudentId {get; set'}
    [Key, Column(Order = 1)]
    public int CourseId {get; set'}
    //extra properties
    [ForeignKey("StudentId")]
    public virtual Student stud { get; set; }
    [ForeignKey("CourseId")]
    public virtual Course course { get; set; }
}

//Controller
var courses = _dbContext.courses.Where(c/*c is "link"*/ => c.Student/*StudentCourse prop*/.Any(s/*link again*/ => s.StudentId == someId/*param*/));//again courses

如您所见,Include不是必需的。

答案 1 :(得分:0)

var result = _dbContext
    .Inscribe.Include(c => c.Courses)
    .Where(c => c.StudentId == studentId)
    .SelectMany(c => c.Courses).ToList();