Skip to content

Advanced Cases

Dima Bezzubenkov edited this page Sep 4, 2021 · 4 revisions

If you know everything that you can accomplish with IQueryable interface then you already know all advanced cases described in this section.

  1. Combine joins and nested select statements

Entity Framework gives you ability to not use joins in 90% of the cases. You just need to have all Navigation Properties in place and IQueryable will generate all necessary joins itself. Also when we do mapping to some external model, we avoid possible problems and performance drawbacks connected with Lazy Loading (in this case we don't have any Lazy Loading):

mappings.Add<Building, BuildingModel, IDbContext>(MappingsNames.BuildingWithReviews, (query, context) => 
    from building in query
    join review in context.Set<Review>() on new { EntityId = building.Id, EntityTypeId = (int) EntityType.Building } 
                                         equals new { EntityId = review.EntityId, EntityTypeId = review.EntityTypeId }
                                         into reviews
    select new BuildingModel
    {
        Id = building.Id,
        Year = building.Year,
        Floors = building.Floors,
        IsLaundry = building.IsLaundry,
        IsParking = building.IsParking,
        Address = new AddressModel
        {
            Id = building.Address.Id,
            BuildingNumber = building.Address.BuildingNumber,
            City = building.Address.City,
            Country = (Countries)building.Address.Country,
            State = building.Address.State,
            Street = building.Address.Street,
            ZipCode = building.Address.ZipCode
        },
        Appartments = building.Appartments.Select(a => new AppartmentModel
        {
            Id = a.Id,
            Badrooms = a.Badrooms,
            Bathrooms = a.Bathrooms,
            Floor = a.Floor,
            IsLodge = a.IsLodge,
            Number = a.Number,
            Size = a.Size.ToString()
        }).ToList(),
        Reviews = reviews.Select(review => new ReviewModel
        {
            Id = review.Id,
            EntityId = review.EntityId,
            EntityType = (EntityType) review.EntityTypeId,
            Rating = review.Rating,
            Comments = review.Comments
        }).ToList()
    });