Данные из двух разных таблиц / моделей - PullRequest
0 голосов
/ 15 ноября 2018

Я пытаюсь отобразить листинг на странице просмотра с данными из 2 разных таблиц / моделей.

(Table1) Table_Service:

  1. Id
  2. Имя

(Table2) Table_Request:

  1. Service_Id
  2. Описание
  3. Запросчик
  4. Статус

Table1 & Table2 связаны по Id / Service_Id.

Моей страницей просмотра должен быть (Table2) листинг Table_Request:

  1. Service_Id
  2. Имя (Из таблицы 1)
  3. Описание
  4. Запрашивающая сторона
  5. Статус

Моя страница просмотра выглядит следующим образом:

@model IEnumerable<OnlinePlatform.Models.ServiceRequests>
<section class="section">
<div class="row">
    <div class="col-md-12">
        <h2>Please choose a service to start</h2>
        <br />
        <div class="row">
            <div class="container">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>Name</th>
                            <th>Description</th>
                            <th>Start Date</th>
                            <th>System Owner</th>
                            <th>Created By</th>
                            <th></th>
                        </tr>
                    </thead>

                    @foreach (var item in Model)
                    {
                        <tbody>
                            <tr>
                                <td>@item.Id</td>

                                <td>@item.Id</td>
                                <td>@item.ServiceId</td>

                                <td>@item.Name</td>

                                <td>@item.RequestorId</td>
                                <td>@item.Description</td>
                                <td>@item.Status</td>

                                <td><button type="button" class="btn">Edit</button></td>
                            </tr>
                        </tbody>
                    }
                </table>
            </div>
        </div>
    </div>
</div>

Мой контроллер работает так:

public ActionResult Service_Request()
    {
        var dao = new ServicesDAO();
        return PartialView("Service_Request", dao.ServiceRequestGetAll().ToList());
    }

public IQueryable<ServiceRequests> ServiceRequestGetAll()
    {
        var result = DB.ServiceRequests.OrderBy(r => r.Id);
        return result;
    }

Как отобразить имя, которое взято из (Table1) Table_Service?

Ответы [ 3 ]

0 голосов
/ 15 ноября 2018

Я бы порекомендовал вам создать такую ​​службу:

IServiceManager.cs :

public interface IServiceManager
{
    IEnumerable<ServiceRequests> GetAllServiceRequests();

    Service GetService(string serviceId);
}

ServiceManager.cs :

public class ServiceManager : IServiceManager
{
    public ApplicationDbContext _dbContext { get; set; }

    public ServiceRequest(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public IEnumerable<ServiceRequests> GetAllServiceRequests()
        => _dbContext.ServiceRequests.OrderBy(r => r.Id);

    public Service GetService(string serviceId)
        => !string.IsNullOrEmpty(serviceId) 
               ? _dbContext.Services.SingleOrDefault(x => x.Id == serviceId) : null;
}

Startup.cs :

services.AddTransient<IServiceManager, ServiceManager>();

Контроллер :

public ActionResult Service_Request()
{
    return View();
}

Service_Request.cshtml:

@model IEnumerable<OnlinePlatform.Models.ServiceRequests>
@inject IServiceManager serviceManager

@foreach (var request in serviceManager.GetAllServiceRequests())
{
    var service = serviceManager.GetService(request.Service_Id);

    <!-- you can use @service.Name here... -->
}
0 голосов
/ 15 ноября 2018

Поскольку вы хотите, чтобы смешанный набор результатов возвращался как IQueryable<T>, следует использовать запрос Join() и поместить результаты запроса в модель представления:

1) Лямбда-версия

public IEnumerable<ServiceRequestsVM> ServiceRequestGetAll()
{
    var result = DB.ServiceRequests.Join(DB.Services,
                                         x => x.Service_Id, // Source table foreign key
                                         y => y.Id, // Joined table primary key
                                         (x, y) => new ServiceRequestsVM { Id = x.Id, Service_Id = x.Service_Id, Name = y.Name, Description = x.Description, Requestor = x.Requestor, Status = x.Status })
                                        .OrderBy(z => z.Service_Id).ToList();

    return result;
}

2) Версия выражения запроса

public IEnumerable<ServiceRequestsVM> ServiceRequestGetAll()
{
    var result = (from srv in DB.Services
                 join srq in DB.ServiceRequests
                 on srv.Id equals srq.Service_Id
                 select new ServiceRequestsVM
                 {
                     Id = srq.Id,
                     Service_Id = srq.Service_Id,
                     Name = srv.Name,
                     Description = srq.Description,
                     Requestor = srq.Requestor,
                     Status = srq.Status
                 }).OrderBy(z => z.Service_Id).ToList();
    return result;
}

Пример Viewmodel

public class ServiceRequestsVM
{
    public int Id { get; set; }
    public int Service_Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Requestor { get; set; }
    public string Status { get; set; }
}

Затем измените директиву @model, чтобы использовать viewmodel с объединенными свойствами из обеих таблиц:

@model IEnumerable<OnlinePlatform.Models.ServiceRequestsVM>

И контроллер должен выглядеть следующим образом:

public ActionResult Service_Request()
{
    var dao = new ServicesDAO();
    return PartialView("Service_Request", dao.ServiceRequestGetAll());
}

После выполнения этих шагов привязка модели должна работать в целом.

0 голосов
/ 15 ноября 2018

Получить записи путем объединения в две таблицы, используя ID ..

FYI ниже,

var result= from req in DB.Table_Request
            join service in DB.Table_Service
            on req.Service_id equals  service.id
           select new ServiceRequests
           {
             Name=service.Name,
             ServiceID=req.Service_Id,

             // Followed model Properties 
            }.ToList();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...