Как вернуть свойства объекта через Result

1

Я пытаюсь получить все свойства объекта. Я не уверен, как это сделать с типом отношений, которые я использую. Я возвращаю все задания в db. У рабочих есть отношения "один ко многим" с классом CustomerEmployee. Мне нужны все свойства класса CustomerEmployee, доступные через список Job. Мне удалось получить первое и последнее имя CustomerEmployee, но я не вижу, как я могу получить доступ к другим свойствам, используя этот способ. Поэтому я не знаю, нужно ли мне изменить способ установки отношений? Это приводит меня к следующему вопросу, когда я создаю новый Job Post, внешний ключ не вставлен в правый столбец. ДБ имеет два разных столбца. Например, "JobTESPMId" и "JobTESPMId_EmployeeId". Мне нужен идентификатор, вставленный в "JobTESPMId_EmployeeId", но он вставлен в другой. Я немного потерялся при настройке, поэтому я хотел бы понять, почему это происходит.

public class Job
{
    public Int64? JobId { get; set; }
    public int? JobNumber { get; set; }
    public string JobName { get; set; }
    public string JobDescription { get; set; }

    public int? GeoAreaId { get; set; }
    public virtual JobMisc.GeoArea GeoArea { get; set; }

    public int? JobClassId { get; set; }
    public virtual JobMisc.JobClass JobClass { get; set; }

    public int? JobTypeId { get; set; }
    public virtual JobMisc.JobType JobType { get; set; }

    public Int64? CustomerId { get; set; }
    public virtual Customer Customer { get; set; }

    public virtual ICollection<ChangeOrder> ChangeOrders { get; set; }
    public virtual ICollection<PurchaseOrder> PurchaseOrders { get; set; }
    public virtual ICollection<JobItem> JobItems { get; set; }

    public int? CustomerEmployeePMId { get; set; }
    public virtual CustomerEmployee CustomerEmployeePM { get; set; }

    public int? CustomerEmployeeAdminId { get; set; }
    public virtual CustomerEmployee CustomerEmployeeAdmin { get; set; }

    public int? CustomerEmployeeAccountantId { get; set; }
    public virtual CustomerEmployee CustomerEmployeeAccountant { get; set; }

    public int? CustomerEmployeeSuperintendentId { get; set; }
    public virtual CustomerEmployee CustomerEmployeeSuperintendent { get; set; }

    public int? JobTESPMId { get; set; }
    public virtual Employee JobTESPM { get; set; }

    public int? JobTESSuperintendentId { get; set; }
    public virtual Employee JobTESSuperintendent { get; set; }
}

CustomerEmployee

public class CustomerEmployee
{
    [Key]
    public int CustomerEmployeeId { get; set; }
    public string CustomerEmployeeFirstName { get; set; }
    public string CustomerEmployeeLastName { get; set; }
    public string CustomerEmployeeEmail { get; set; }
    public Int64? CustomerEmployeePhoneNumber { get; set; }
    public Int64? CustomerEmployeeCellNumber { get; set; }
    public Int64? CustomerEmployeeFaxNumber { get; set; }
    public bool? CustomerEmployeeIsHidden { get; set; }
    public string CustomerEmployeeRole { get; set; }

    public Int64? CustomerId { get; set; }
    public virtual Customer Customer { get; set; }

}

ViewModel/Результат

 public class JobViewModel
  {
    public Int64? JobId { get; set; }
    public int? JobNumber { get; set; }
    public string JobName { get; set; }
    public decimal? JobOriginalContract { get; set; }
    public DateTime? JobContractDate { get; set; }
    public decimal? JobTotalCO { get; set; }
    public decimal? JobRevisedContract { get; set; }
    public decimal? JobOriginalBudget { get; set; }
    public string JobStatus { get; set; }
    public bool? JobTaxExempt { get; set; }
    public bool? JobCertPayroll { get; set; }
    public decimal? JobCost { get; set; }
    public decimal? JobRemainingBudget { get; set; }
    public decimal? JobProfit { get; set; }
    public decimal? JobPercentage { get; set; }
    public decimal? JobTotalBilled { get; set; }
    public decimal? JobBalanceToBill { get; set; }
    public decimal? JobPaidToDate { get; set; }
    public decimal? JobBalanceDue { get; set; }
    public bool? JobIsHidden { get; set; }


    public string Customer { get; set; }
    public string CustomerEmployeePM { get; set; }
    public string JobTESPM { get; set; }
    public string JobTESSuperintendent { get; set; }
    public IEnumerable<ChangeOrder> ChangeOrders { get; set; }
    public IEnumerable<PurchaseOrder> PurchaseOrders { get; set; }

  }

 public class JobResult
  {
    public Int64? JobId { get; set; }
    public int? JobNumber { get; set; }
    public string JobName { get; set; }
    public decimal? JobOriginalContract { get; set; }
    public DateTime? JobContractDate { get; set; }
    public decimal? JobTotalCO { get; set; }
    public decimal? JobRevisedContract { get; set; }
    public decimal? JobOriginalBudget { get; set; }
    public string JobStatus { get; set; }
    public bool? JobTaxExempt { get; set; }
    public bool? JobCertPayroll { get; set; }
    public decimal? JobCost { get; set; }
    public decimal? JobRemainingBudget { get; set; }
    public decimal? JobProfit { get; set; }
    public decimal? JobPercentage { get; set; }
    public decimal? JobTotalBilled { get; set; }
    public decimal? JobBalanceToBill { get; set; }
    public decimal? JobPaidToDate { get; set; }
    public decimal? JobBalanceDue { get; set; }
    public bool? JobIsHidden { get; set; }


    public string Customer { get; set; }
    public string CustomerEmployeePM { get; set; }
    public string JobTESPM { get; set; }
    public string JobTESSuperintendent { get; set; }
    public IEnumerable<ChangeOrder> ChangeOrders { get; set; }
    public IEnumerable<PurchaseOrder> PurchaseOrders { get; set; }
 }

apiController

// GET api/<controller>
    public IEnumerable<JobResult> Get()
    {
        using (var context = new ApplicationDbContext())
        {
            return context.Jobs
                .Include(x => x.Customer)
                .Include(x => x.ChangeOrders)
                .Include(x => x.PurchaseOrders)
                .Include(x => x.CustomerEmployeePM)
                .Include(x => x.JobTESPM)
                .Include(x => x.JobTESSuperintendent)

                .ToResults();
        }

    }

JSON

0: {$id: "1", JobId: 2, JobNumber: 3244, JobName: "Job Alpha", JobOriginalContract: 34343443,…}
$id: "1"
ChangeOrders: [,…]
Customer: "Twin Peaks"
CustomerEmployeePM: "Kelly Young"
JobId: 2
JobName: "Job Alpha"
JobNumber: 3244
JobTESPM: "Laura Mince"
JobTESSuperintendent: "Scott Willis"
JobTaxExempt: true
JobTotalBilled: null
PurchaseOrders: []
1: {$id: "3", JobId: 9, JobNumber: 342, JobName: "sad", JobOriginalContract: 323232,…}
Теги:
asp.net-web-api2
asp.net-mvc-5.1
asp.net-mvc-viewmodel

2 ответа

0

Возможно, один быстрый ответ, если у вашего класса JobResult был конструктор, который позволял вам отображать от Job to JobResult, тогда это было бы так же просто, как

return context.Jobs
  .Select(j => new JobResult(j));

или если вы предпочитаете менее связанный способ...

return context.Jobs
  .Select(j => new JobResult(j.Customer, j.ChangeOrders, j.PurchaseOrders, etc.));

По сути, вы имеете дело с отображением от одного типа к другому. Подобная работа по составлению карт - это то, как вы решаете свой второй вопрос.

Изменение: немного туманно по моим способностям EF, но вам может понадобиться пустой конструктор, и в этом случае что-то вроде этого... Я вроде забыл, что разрешено в запросе linq, но я знаю, что работает пустой конструктор.

return context.Jobs
  .Select(j => new JobResult() { j.Customer, j.ChangeOrders, j.PurchaseOrders, etc.} );

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

return context.Jobs
  .ToList()
  .Select(j => new JobResult() { j.Customer, j.ChangeOrders, j.PurchaseOrders, etc.} );
  • 0
    Как бы я добавить конструктор в класс Result?
0
return context.Jobs
                .Include(x => x.Customer)
                .Include(x => x.ChangeOrders)
                .Include(x => x.PurchaseOrders)
                .Include(x => x.CustomerEmployeePM)
                .Include(x => x.JobTESPM)
                .Include(x => x.JobTESSuperintendent)

                .ToList(); 

это то, что вам нужно

  • 0
    Когда я изменяю его на List, я получаю эту ошибку 2 Не могу неявно преобразовать тип 'System.Collections.Generic.List <TexasExteriorSPA.Models.Job>' в 'System.Collections.Generic.IEnumerable <TexasExteriorSPA.Models.JobResult>'. Существует явное преобразование (вам не хватает приведения?) C: \ Development \ TexasExteriorSPA \ TexasExteriorSPA \ ApiControllers \ apiJobController.cs 34 21 TexasExteriorSPA

Ещё вопросы

Сообщество Overcoder
Наверх
Меню