Как объединить таблицы из нескольких dbcontexts в одну ViewModel?C#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Гость
 Как объединить таблицы из нескольких dbcontexts в одну ViewModel?

Сообщение Гость »

Итак, у меня есть два контекста базы данных для получения данных из разных таблиц, и я хочу объединить их в ViewModel. Я знаю, что мне, вероятно, следует использовать .Join(), но мне интересно, возможно ли что-то подобное:
Мой контроллер:

Код: Выделить всё

public class HomeController : Controller
{
private readonly NAV_FS_DBContext _navContext;
private readonly DostebaPpsContext _baseDataContext;

public HomeController(NAV_FS_DBContext navContext, DostebaPpsContext baseDataContext)
{
_navContext = navContext;
_baseDataContext = baseDataContext;
}

// GET: Home
public async Task Index()
{
List speweSalesList = await _navContext.SpeweSalesLines.ToListAsync();
List spewePoList = await _navContext.SpeweProdOrderLines.ToListAsync();
List baseDataList = await _baseDataContext.Variables.ToListAsync();
List poItems = await _navContext.SpeweProductionOrder
.Select(x => new PoItemViewModel
{
Status = x.Status,
PONr = x.No,
ItemNr = x.SourceNo,
FormType = x.Description,
Quantity = x.Quantity,
StartingDate = x.StartingDate,
EndingDate = x.EndingDate,
ShipmentDate = speweSalesList.Where(y => y.No == x.No).Select(y => y.ShipmentDate).FirstOrDefault(),
Priority = spewePoList.Where(y => y.ProdOrderNo == x.No).Select(y => y.Priority).FirstOrDefault(),
Molds = baseDataList.Where(y => y.SourceNo == x.SourceNo).Select(y => y.MoldPerDay).FirstOrDefault()
}).ToListAsync();

return View(poItems);
}
}
Модель представления:

Код: Выделить всё

public class PoItemViewModel
{
public string? ItemNr { get; set; }
public int? Status { get; set; }
public string? FormType { get; set; }
public decimal? Quantity { get; set; }
public int? Molds { get; set; }
public decimal? Days { get; set; }
public string? PONr { get; set; }
public DateTime? StartingDate { get; set; }
public DateTime? EndingDate { get; set; }
public DateTime? ShipmentDate { get; set; }
public int? Priority { get; set; }
}
NAV_FS_DBContext:

Код: Выделить всё

public partial class NAV_FS_DBContext : DbContext
{
public NAV_FS_DBContext()
{
}

public NAV_FS_DBContext(DbContextOptions options)
: base(options)
{
}

public virtual DbSet SpeweItem { get; set; }
public virtual DbSet SpeweProductionOrder { get; set; }

public virtual DbSet SpeweItemLedgerEntries { get; set; }

public virtual DbSet SpeweSalesLines { get; set; }

public virtual DbSet SpeweValueEntries { get; set; }
public virtual DbSet SpeweProdOrderLines { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer("Name=ConnectionStrings:CS2");

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.UseCollation("Latin1_General_100_CI_AS");

modelBuilder.Entity(entity =>
{
entity.HasKey(e => e.No).HasName("SPEWE$Item$0");

entity.ToTable("SPEWE$Item", "dbo");
//etc...
});
OnModelCreatingPartial(modelBuilder);
}

partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
Модель SpeweProductionOrder (из dbcontext):

Код: Выделить всё

public partial class SpeweProductionOrder
{
public byte[] Timestamp { get; set; } = null!;

public int Status { get; set; }

public string No { get; set; } = null!;

public string Description { get; set; } = null!;

public string SearchDescription { get; set; } = null!;

public string Description2 { get; set; } = null!;

public DateTime CreationDate { get; set; }

public DateTime LastDateModified { get; set; }

public int SourceType { get; set;  }

public string SourceNo { get; set; } = null!;

public string RoutingNo { get; set; } = null!;

public string InventoryPostingGroup { get; set; } = null!;

public string GenProdPostingGroup { get; set; } = null!;

public string GenBusPostingGroup { get; set; } = null!;

public DateTime StartingTime { get; set; }

public DateTime StartingDate { get; set; }

public DateTime EndingTime { get; set; }

public DateTime EndingDate { get; set; }

public DateTime DueDate { get; set; }

public DateTime FinishedDate { get; set; }

public byte Blocked { get; set; }

public string ShortcutDimension1Code { get; set; } = null!;

public string ShortcutDimension2Code { get; set; } = null!;

public string LocationCode { get; set; } = null!;

public string BinCode { get; set; } = null!;

public string ReplanRefNo { get; set; } = null!;

public int ReplanRefStatus { get; set; }

public int LowLevelCode { get; set; }

public decimal Quantity { get; set; }

public decimal UnitCost { get; set; }

public decimal CostAmount { get; set; }

public string NoSeries { get; set; } = null!;

public string PlannedOrderNo { get; set; } = null!;

public string FirmPlannedOrderNo { get; set; } = null!;

public string SimulatedOrderNo { get; set; } = null!;

public DateTime StartingDateTime { get; set; }

public DateTime EndingDateTime { get; set; }

public int DimensionSetId { get; set; }

//etc...
}

Модель SpeweSalesLine (из dbcontext):

Код: Выделить всё

public partial class SpeweSalesLine
{
public byte[] Timestamp { get; set; } = null!;

public int DocumentType { get; set; }

public string DocumentNo { get; set; } = null!;

public int LineNo { get; set; }

public string SellToCustomerNo { get; set; } = null!;

public int Type { get; set; }

public string No { get; set; } = null!;

public string LocationCode { get; set; } = null!;

public string PostingGroup { get; set; } = null!;

public DateTime ShipmentDate { get; set; }

public string Description { get; set; } = null!;

public string Description2 { get; set; } = null!;

public string UnitOfMeasure { get; set; } = null!;

public decimal Quantity { get; set; }

public decimal OutstandingQuantity { get; set; }

public decimal QtyToInvoice { get; set; }

public decimal QtyToShip { get; set; }

public decimal UnitPrice { get; set; }

public decimal UnitCostLcy { get; set; }

public decimal Vat { get; set; }

public decimal LineDiscount { get; set; }

public decimal LineDiscountAmount { get; set; }

public decimal Amount { get; set; }

public decimal AmountIncludingVat { get; set; }

public byte AllowInvoiceDisc { get; set; }

public decimal GrossWeight { get; set; }

public decimal NetWeight { get; set; }

public decimal UnitsPerParcel { get; set; }

public decimal UnitVolume { get; set; }

public int ApplToItemEntry { get; set; }

public string ShortcutDimension1Code { get; set; } = null!;

public string ShortcutDimension2Code { get; set; } = null!;

public string CustomerPriceGroup { get; set; } = null!;

public string JobNo { get; set; } = null!;

public string WorkTypeCode { get; set; } = null!;

public byte RecalculateInvoiceDisc { get; set; }

public decimal OutstandingAmount { get; set; }

public decimal QtyShippedNotInvoiced { get; set; }

public decimal ShippedNotInvoiced { get; set; }

public decimal QuantityShipped { get; set; }

public decimal QuantityInvoiced { get; set; }

public string ShipmentNo { get; set; } = null!;

public int ShipmentLineNo { get; set; }

public decimal Profit { get; set; }

public string BillToCustomerNo { get; set; } = null!;

public decimal InvDiscountAmount { get; set; }

public string PurchaseOrderNo { get; set; } = null!;

public int PurchOrderLineNo { get; set; }

public byte DropShipment { get; set; }

public string GenBusPostingGroup { get; set;  } = null!;

public string GenProdPostingGroup { get; set; } = null!;

public int VatCalculationType { get; set; }

public string TransactionType { get; set; } = null!;

public string TransportMethod { get; set; } = null!;

public int AttachedToLineNo { get; set; }

public string ExitPoint { get; set; } = null!;

public string Area { get; set; } = null!;

public string TransactionSpecification { get; set; } = null!;

public string TaxCategory { get; set; } = null!;

public string TaxAreaCode { get; set; } = null!;

public byte TaxLiable { get; set; }

public string TaxGroupCode { get; set; } = null!;

public string VatClauseCode { get; set; } = null!;

public string VatBusPostingGroup { get; set; } = null!;

public string VatProdPostingGroup { get; set; } = null!;

public string CurrencyCode { get; set; } = null!;

public decimal OutstandingAmountLcy { get; set; }

public decimal ShippedNotInvoicedLcy { get; set; }

public int Reserve { get; set; }

public string BlanketOrderNo { get; set; } = null!;

public int BlanketOrderLineNo { get; set; }

public decimal VatBaseAmount { get; set; }

public decimal UnitCost { get; set; }

public byte SystemCreatedEntry { get; set; }

public decimal LineAmount { get; set; }

public decimal VatDifference { get; set; }

public decimal InvDiscAmountToInvoice { get; set; }

public string VatIdentifier { get; set; } = null!;

public int IcPartnerRefType { get; set; }

public string IcPartnerReference { get; set; } = null!;

public decimal Prepayment { get; set; }

public decimal PrepmtLineAmount { get; set; }

public decimal PrepmtAmtInv { get; set; }

public decimal PrepmtAmtInclVat { get; set; }

public decimal PrepaymentAmount { get; set; }

public decimal PrepmtVatBaseAmt { get; set; }

public decimal PrepaymentVat { get; set; }

public int PrepmtVatCalcType { get; set; }

public string PrepaymentVatIdentifier { get; set; } = null!;

public string PrepaymentTaxAreaCode { get; set; } = null!;

public byte PrepaymentTaxLiable { get; set; }

public string PrepaymentTaxGroupCode { get; set; } = null!;

public decimal PrepmtAmtToDeduct { get; set; }

public decimal PrepmtAmtDeducted { get; set; }

public byte PrepaymentLine { get; set; }

public decimal PrepmtAmountInvInclVat { get; set; }

public decimal PrepmtAmountInvLcy { get; set; }

public string IcPartnerCode { get; set; } = null!;

public decimal PrepmtVatAmountInvLcy { get; set; }

public decimal PrepaymentVatDifference { get; set; }

public decimal PrepmtVatDiffToDeduct { get; set; }

public decimal PrepmtVatDiffDeducted { get; set; }

public int DimensionSetId { get; set; }

public decimal QtyToAssembleToOrder { get; set; }

public decimal QtyToAsmToOrderBase { get; set; }

public string JobTaskNo { get; set; } = null!;

public int JobContractEntryNo { get; set; }

public string DeferralCode { get; set; } = null!;

public DateTime ReturnsDeferralStartDate { get; set; }

//etc...
}
Модель переменных (из dbcontext)

Код: Выделить всё

public partial class Variable
{
public string SourceNo { get; set; } = null!;

public string Type { get; set; } = null!;

public int PiecePerPallett { get; set; }

public int Lotsize { get; set; }

public int MoldPerDay { get; set; }

public int FormAmount { get; set; }

public int CavityAmount { get; set; }

public decimal FormTime { get; set; }

public decimal FillTime { get; set; }

public decimal CarouselRotation { get; set; }

public decimal CompletionTime { get; set; }

public decimal Cycle { get; set; }
}
Очевидно, что это не работает, поскольку я получаю исключение InvalidOperationException, но я имею в виду, что я заранее загружаю все данные и сохраняю их в виде списка, так почему я не могу получить/сравнить данные откуда, например, "spewePoList"?
Было бы неплохо узнать некоторые мысли по этому поводу, и заранее благодарю вас за помощь.

Подробнее здесь: https://stackoverflow.com/questions/781 ... -viewmodel
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Использование нескольких EF Core DbContexts в одном приложении в чистой архитектуре
    Anonymous » » в форуме C#
    0 Ответы
    35 Просмотры
    Последнее сообщение Anonymous
  • Entity Framework Core с использованием нескольких DbContexts
    Anonymous » » в форуме C#
    0 Ответы
    30 Просмотры
    Последнее сообщение Anonymous
  • Использование TransactionScope для нескольких DbContexts и добавление механизма повтора
    Anonymous » » в форуме C#
    0 Ответы
    18 Просмотры
    Последнее сообщение Anonymous
  • Использование TransactionScope для нескольких DbContexts и добавление механизма повтора
    Anonymous » » в форуме C#
    0 Ответы
    18 Просмотры
    Последнее сообщение Anonymous
  • Использование TransactionScope для нескольких DbContexts и добавление механизма повтора
    Anonymous » » в форуме C#
    0 Ответы
    8 Просмотры
    Последнее сообщение Anonymous

Вернуться в «C#»