简体   繁体   中英

LINQ: Group by and Join

I have 2 models:

public partial class Movie
{
    public Movie()
    {
        TimeTables = new HashSet<TimeTable>();
    }

    [Key]
    public int MovieId { get; set; }
    public string MovieName { get; set; }
    public int MovieGenre { get; set; }
    public string MoviePicture { get; set; }
    public string MovieDescription { get; set; }
    public string MovieShortText { get; set; }
    public bool? MovieIs3d { get; set; }
    public bool? MovieIsImax { get; set; }
    public int MovieLanguage { get; set; }
    public bool? MovieSubtitled { get; set; }
    public int? MovieMinimalAge { get; set; }
    public bool? MovieHasDrugs { get; set; }
    public bool? MovieHasViolence { get; set; }
    public bool? MovieHasSex { get; set; }
    public bool? MovieHasSwearing { get; set; }
    public bool? MovieIsScary { get; set; }
    public bool? MovieHasDiscrimination { get; set; }
    public string MovieTrailer { get; set; }
    public int MovieLength { get; set; }
    public int? Genre_GenreId { get; set; }
    public int? Language_LanguageId { get; set; }
    public virtual Genre Genre { get; set; }
    public virtual Language Language { get; set; }
    public virtual ICollection<TimeTable> TimeTables { get; set; }
}

And:

public partial class TimeTable
{
    public TimeTable()
    {
        Reservations = new HashSet<Reservation>();
    }
    public int TimeTableId { get; set; }
    public int MovieId { get; set; }
    public int RoomId { get; set; }
    public int SeatsAvaible { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
    public virtual Movie Movie { get; set; }
    public virtual ICollection<Reservation> Reservations { get; set; }
    public virtual Room Room { get; set; }
}

I want to show all the records from Movie which have one or more records in TimeTable and where StartDate.date == [given datetime]. With a simple query the movies are showing multiple times. I have tried a distinct() but that changes nothing. Anybody here who have the solution?

Current query:

var times2 =
            (from s in timetablerepo.TimeTables
             orderby s.StartTime.TimeOfDay
             where s.StartTime.Date == datetime.Date
             select s).Distinct().ToList();

Why not start with movies first and filter by timetable:

var times = timetablerepo.Movies
            .Where(m => m.TimeTables.Any(t => t.StartDate.Date == <yourdate>));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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