Запрос объектов для отношения один ко многим в LINQ - PullRequest
0 голосов
/ 16 декабря 2018

У меня есть проблема, которая, похоже, очень похожа на
Запрос объектов для отношения один ко многим в LINQ

Я пытался решить мою проблему, ссылаясь на приведенное вышено почему-то я долго терпел неудачу.

Сценарий
У меня есть модель с именем Business, которая имеет ICollection of Branches, а также бизнес принадлежит определенной Подкатегория .

Модель выглядит примерно так:

public class SubCategory
{
    public string Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public string ImageUrl { get; set; }

    public string Category_FK { get; set; }

    public Category Category { get; set; }

    [ForeignKey("SubCategory_FK")]
    public ICollection<Business> Businesses { get; set; }

    public SubCategory(){
        Businesses = new Collection<Business>();
    }
}

public class Business
{
    public string Id { get; set; }

    public string Name { get; set; }

    public string Email { get; set; }

    public string HeadquartersContact { get; set; }

    public string ImageUrl { get; set; }

    public SubCategory SubCategory { get; set; }

    public string SubCategory_FK { get; set; }
    [ForeignKey("Business_Fk")]
    public ICollection<Branch> Branches { get; set; }

    public Business()
    {
        Branches = new Collection<Branch>();
    }
}

А модель ветви выглядит как

public class Branch
{
    public string Id { get; set; }

    public string Name { get; set; }

    public string Phone { get; set; }

    public string ImageUrl { get; set; }

    public Business Business { get; set; }

    public string Business_Fk { get; set; }

    [ForeignKey("Location_FK")]
    public Location Location { get; set; }

    public string Location_FK { get; set; }

    [ForeignKey("Branch_FK")]
    public ICollection<BranchImage> BranchImages { get; set; }

    public Branch()
    {
        BranchImages = new Collection<BranchImage>();
    }
}

Каждая ветвь может иметь одно местоположение.Ниже приведена модель местоположения

public class Location
    {
        public string Id { get; set; }

        public string Name { get; set; }

        public decimal Lattitude { get; set; }

        public decimal Longitude { get; set; }

        public SubLocality SubLocality { get; set; }

        public string SubLocality_FK { get; set; }

        public Branch Branch { get; set; }

        public Location()
        {
        }
    }

Сублокальность может иметь ICollection of Locations.Вот модель SubLocality

public class SubLocality
{
    public string Id { get; set; }

    public string Name { get; set; }

    public Locality Locality { get; set; }

    public string Locality_FK { get; set; }

    [ForeignKey("SubLocality_FK")]
    public ICollection<Location> Locations { get; set; }

    public SubLocality()
    {
        Locations = new Collection<Location>();
    }


}

Места могут иметь ICollection of Sublocality

public class Locality
{
    public string Id { get; set; }

    public string Name { get; set; }

    public City City { get; set; }

    public string City_FK { get; set; }
    [ForeignKey("Locality_FK")]
    public ICollection<SubLocality> SubLocalities { get; set; }

    public Locality()
    {
        SubLocalities = new Collection<SubLocality>();
    }
}

Город может иметь ICollection of Localities.

public class City
{
    public string Id { get; set; }

    public string Name { get; set; }

    public State State { get; set; }

    public string State_FK { get; set; }
    [ForeignKey("City_FK")]
    public ICollection<Locality> Localities { get; set; }

    public City()
    {
        Localities = new Collection<Locality>();
    }
}

И, наконец, состояниеможет иметь коллекцию городов.

public class State
{
    public string Id { get; set; }

    public string Name { get; set; }

    [ForeignKey("State_FK")]
    public ICollection<City> Cities { get; set; }

    public State()
    {
        Cities = new Collection<City>();
    }
}

Вот мой DataContext , экземпляры которого я использую в запросе для извлечения данных.

public class DataContext : DbContext
{
    public DataContext(DbContextOptions<DataContext> options): base (options)
    {

    }

    //-------Business_Info_Models----------------
    public DbSet<Branch> Branches { get; set; }
    public DbSet<BranchImage> BranchImages { get; set; }
    public DbSet<Business> Businesses { get; set; }

    //-------Category_Info_Models----------------
    public DbSet<Category> Categories { get; set; }
    public DbSet<SubCategory> SubCategories { get; set; }

    //-------------Location_Info_Models----------------
    public DbSet<City> Cities { get; set; }
    public DbSet<Locality> Localities { get; set; }
    public DbSet<Location> Locations{ get; set; }
    public DbSet<State> States { get; set; }
    public DbSet<SubLocality> SubLocalities { get; set; }
}

требование
Теперь мне нужно запросить предприятия определенной подкатегории, а также получить все филиалы (например, один бизнес может иметь 8 филиалов, 5 филиалов и т. д.).Это местоположение, расположение, город, штат (упомяну, что я получаю все эти данные из разных таблиц с помощью объединения в LINQ).

Для удовлетворения этого требования я использую DTO (объект передачи данных).

public class AddBusinessDto
{
    public string Id { get; set; }

    public string Name { get; set; }

    public string Email { get; set; }

    public string HeadquartersContact { get; set; }

    public string ImageUrl { get; set; }

    public string SubCategory_FK  { get; set; }

    public ICollection<AddBranchDto> Branches { get; set; }
    //public ICollection<AddLocationsDto> Locations {get; set; }
}

public class AddBranchDto
{
    public string Id { get; set; }

    public string Name { get; set; }

    public string Phone { get; set; }

    public string ImageUrl { get; set; }

    public AddLocationsDto Location { get; set; }
    public string Location_FK { get; set; }
}

Запрос LINQ

IQueryable<BusinessDto> query =  (from business in _context.Businesses
        join subcategory in _context.SubCategories on business.SubCategory_FK equals subcategory.Id
        join branch in _context.Branches on business.Id equals branch.Business_Fk 
        join location in _context.Locations on branch.Location_FK equals location.Id
        join sublocal in _context.SubLocalities on location.SubLocality_FK equals sublocal.Id
        join locality in _context.Localities on sublocal.Locality_FK equals locality.Id
        join city in _context.Cities on locality.City_FK equals city.Id
        join state in _context.States on city.State_FK equals state.Id
        where business.SubCategory_FK == subCatId
        select new BusinessDto() {
            Id = business.Id,
            Name = business.Name,
            HeadquartersContact = business.HeadquartersContact,
            Location = location.Name,
            Sublocality = sublocal.Name,
            Locality = locality.Name,
            City = city.Name,
            State = state.Name,
            Email = business.Email,

            Branches = business.Branches
                        .Select(branches => 
                        new BranchDto{Id = branches.Id, Name = branches.Name, Phone = branches.Phone})
                        .Distinct()
                        .ToList()
        });

Я почти достиг результата, но это BUG с этим запросом:

The buggy output

Вышеуказанный бизнес в СС имеет 8 филиалов.В идеале я должен получить только одну карту в пользовательском интерфейсе, которая показывает данные о 8 ветвях, когда я наведите на них значок ветки.

Но запрос дает мне 8 карточек такого типа.Как мне это решить.Пожалуйста, помогите!

...