从一对多的情况如何获取实体框架中的常见项目

Mis*_*tyD 5 c# entity-framework

我刚刚开始使用实体框架,在为以下情况生成查询时遇到困难。

我目前有两个模型类StudentSport. 一个学生可以参加多种运动。这就是我的模型的样子

public class DbContext : DbContext
{
        public DbContext(): base("name=DbContext")
        {
        }

        public DbSet<Student> MyStudents { get; set; }
        public DbSet<Sport> MySports { get; set; }
}

public class Student
{
    public List<Sport> Actions { get; set; }

    public string Name { get; set; }
}

public class Sport
{
    public string SportName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是如何获得所有学生参加的所有运动项目的列表?总之我正在寻找共同的运动。所以基本上在以下情况

Student A played Sports : Soccer , Tennis , Bowling
Student B played Sports : Soccer , Tennis , 
Student C played Sport  : Tennis
Run Code Online (Sandbox Code Playgroud)

那么只有 Tennis 应该被返回

小智 4

使用您提供的数据库模式,您可以获得每个学生的常见运动检查运动:

var sports = new[]
{
    new Sport { SportName = "Tennis" },
    new Sport { SportName = "Soccer" },
    new Sport { SportName = "Bowling" }
};

var students = new[]
{
    new Student
    {
        Name = "Student 1",
        Actions = sports
    },
    new Student
    {
        Name = "Student 2",
        Actions = new[] { sports[0], sports[1] }
    },
    new Student
    {
        Name = "Student 3",
        Actions = new[] { sports[0] }
    }
};

// Or
var sports = context.Sports;
var students = context.Students;

// In case students' sports are objects (as in this sample) you can use such a query:
var commonSports = sports.Where(sport =>
    students.All(student => student.Actions.Contains(sport)));
// In case you're going to check the sports by name, this:
var commonSports = sports.Where(sport =>
    students.All(student => student.Actions.Any(studSport => 
         studSport.SportName == sport.SportName)));
Console.WriteLine($"Comon sports: {string.Join(",", commonSports.Select(i => i.SportName))}");
// To get only names of common sports:
var sportNames = commonSports.Select(i => i.SportName);
Console.Read();
Run Code Online (Sandbox Code Playgroud)

如果您使用关系数据库,那么实现多对多关系会更容易并且(对我来说)更符合逻辑,如下所述