question

Cenk-1028 avatar image
0 Votes"
Cenk-1028 asked Cenk-1028 answered

EF Core - updated data retrieve problem

Hello,

I am trying to get updated data like this in my Blazor Server application:

 async Task PassiveDetail(OrderDetail orderDetail)
     {
         if (orderDetail == _detailToInsert)
         {
             _detailToInsert = null;
         }
    
            
         await PassiveOrderDetailUseCase.ExecuteAsync(orderDetail);  //Updates a value
            
         _orders = await ViewAllOrdersUseCase.ExecuteAsync(user); // Retrieves data but not updated!
         StateHasChanged();
    
     }

Here is how I update a value:

 public async Task PassiveOrderDetailAsync(OrderDetail orderDetail)
         {
               
             var detail = await this._db.OrdersDetail.FindAsync(orderDetail.Id);
             if (detail != null)
             {
                    
                 detail.IsActive = 0; // 0-Passive
                    
                 await _db.SaveChangesAsync();
             }
         }

Here is how I retrieve:

 public async Task<IEnumerable<Order?>> GetAllOrders(ClaimsPrincipal user)
         {
             if (user.IsInRole("Administrators"))
             {
                 return await _db.Orders.Include(d => d.OrderDetails.Where(od => od.IsActive == 1)).ThenInclude(v => v.Vendor).ToListAsync(); ;
             }
                
             return await _db.Orders.Include(d => d.OrderDetails.Where(od => od.IsActive == 1)).ThenInclude(v => v.Vendor).ToListAsync();
    
         }

When I refresh the page the data is updated, what is the problem? Any ideas?

dotnet-aspnet-core-blazordotnet-entity-framework-core
· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @Cenk-1028,

When I refresh the page the data is updated, what is the problem? Any ideas?

   await PassiveOrderDetailUseCase.ExecuteAsync(orderDetail);  //Updates a value
     _orders = await ViewAllOrdersUseCase.ExecuteAsync(user); // Retrieves data but not updated!

Your question is not clear, please explain more detail about it? Do you mean after calling the execute method to update the value, if you retrieve the data, it still get the old data? If that is the case, check your ViewAllOrdersUseCase.ExecuteAsync method.

0 Votes 0 ·

Your question is not clear, please explain more detail about it? Do you mean after calling the execute method to update the value, if you retrieve the data, it still get the old data?

Yes, exactly what is happening.

But if there is a problem with ViewAllOrdersUseCase.ExecuteAsync method, after page refresh why do I get the new data? I don't understand.

Is it due to your reply to this post https://docs.microsoft.com/en-us/answers/questions/1008629/linq-theninclude-where-problem.html




0 Votes 0 ·

After await PassiveOrderDetailUseCase.ExecuteAsync(orderDetail); method I check the database, it sets to IsActive = 0, so no problem with updating the data. But when I debug this _orders = await ViewAllOrdersUseCase.ExecuteAsync(user); method, still I see this updated detail IsActive = 1 .

This transaction is going on a Blazor Server blazor page and if I refresh the page this updated order detail disappears as it is excepted. But why it is not working without refresh?

0 Votes 0 ·
Cenk-1028 avatar image
0 Votes"
Cenk-1028 answered Cenk-1028 edited

Here is the Blazor Page for the transaction I mention, retrieving correct on OnInitializedAsync method but it is not working on async Task PassiveDetail(OrderDetail orderDetail) why it is not ?

 @page "/orders"
    
 @using IMS.CoreBusiness
 @using IMS.Plugins.EFCore.Migrations
 @using IMS.UseCases.Interfaces.Order
 @using IMS.UseCases.Interfaces.OrderDetail
 @using System.Globalization
 @using System.Security.Claims
 @using IMS.UseCases.Interfaces.Customer
 @using IMS.UseCases.Interfaces.Vendor
 @using Vendor = IMS.CoreBusiness.Vendor
 @using OfficeOpenXml
 @using OfficeOpenXml.Style
    
    
 @inject NavigationManager NavigationManager
 @inject IViewAllOrdersUseCase ViewAllOrdersUseCase
 @inject IAddOrderUseCase AddOrderUseCase
 @inject IEditOrderUseCase EditOrderUseCase
 @inject IAddOrderDetailUseCase AddOrderDetailUseCase
 @inject IEditOrderDetailUseCase EditOrderDetailUseCase
 @inject IViewAllVendorsUseCase ViewAllVendorsUseCase
 @inject IViewOrdersByStatusUseCase ViewOrdersByStatusUseCase
 @inject ICancelOrderUseCase CancelOrderUseCase
 @inject ICancelOrderDetailUseCase CancelOrderDetailUseCase
 @inject IViewAllCustomersUseCase ViewAllCustomersUseCase
 @inject IPassiveOrderDetailUseCase PassiveOrderDetailUseCase
 @inject IJSRuntime JS
 @inject AuthenticationStateProvider _authenticationStateProvider
    
    
    
 <style>
     #wrapper { overflow: auto; }
    
     #c1 { float: right; }
    
     #c2 { float: right; }
    
     #c3 { float: right; }
 </style>
 @if (DisplayAlert) {
     <div class="alert alert-success alert-dismissible d-flex align-items-center fade show">
         <i class="bi-check-circle-fill"></i>
         <strong class="mx-2">Success!</strong> Your message has been sent successfully.
         <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
     </div>
 }
 <h1>Orders</h1>
 <RadzenButton Icon="add_circle_outline" style="margin-bottom: 10px" Text="Add New Order" Click="@InsertRow" Disabled="@(_orderToInsert != null)"/><RadzenButton Text="Export XLS" Icon="grid_on" Click="@(args => ExportExcel())" Class="mb-4 mr-2" />
 <RadzenDataGrid @ref="_grid" AllowFiltering="true" AllowPaging="true" PageSize="7" AllowSorting="true" RowClick="RowClick" ExpandMode="DataGridExpandMode.Single"
                 Data="@_orders" TItem="Order" EditMode="DataGridEditMode.Single" RowUpdate="@OnUpdateRow" RowCreate="@OnCreateRow" @bind-Value="@SelectedOrders"
                 ShowExpandColumn="false" ShowPagingSummary="true" AllowColumnResize="true" >
     <Template Context="order">
         <RadzenCard Style="margin-bottom: 20px">
             Customer:
             <b>@order?.Customer?.Name</b>
         </RadzenCard>
         <RadzenTabs>
             <Tabs>
                 <RadzenTabsItem Text="Order Details">
                     <div id="wrapper">
                         <RadzenButton Icon="add_circle_outline" style="margin-bottom: 10px" Text="Add Order Detail" Click="@(() => InsertDetailRow(order.Id))" Disabled="@(_detailToInsert != null)"/>
                         <RadzenButton Text="Export XLS" Icon="grid_on" Click="@(args => ExportDetailExcel())" Class="mb-4 mr-2" />
                         <RadzenButton Icon="close" id="c3" style="margin-bottom: 10px;" ButtonStyle="ButtonStyle.Light" Click="@(args => CancelEdits(SelectedOrders.FirstOrDefault()?.OrderDetails))" />
                         <RadzenButton Icon="save" style="margin-bottom: 10px; margin-right: 10px" Text="Save Details" id="c2" Click="@(args => SaveRowDetails(SelectedOrders.FirstOrDefault()?.OrderDetails))"/>
                         <RadzenButton Icon="border_color" style="margin-bottom: 10px; margin-right: 10px" Text="Edit Details" id="c1" Click="@(args => EditRowDetails(SelectedOrders.FirstOrDefault()?.OrderDetails))" @onclick:stopPropagation="true"/>
                            
                            
                     </div>
                     <RadzenDataGrid @ref="_gridDetail" AllowFiltering="true" AllowPaging="true" PageSize="5" AllowSorting="true" Data="@order.OrderDetails" 
                     TItem="OrderDetail" EditMode="DataGridEditMode.Multiple" RowUpdate="@OnUpdateRowDetail" RowCreate="@OnCreateRowDetail" AllowColumnResize="true"
                                     AllowColumnPicking="true" ShowPagingSummary="true" ColumnWidth="150px" >
                         <Columns>
    
                             <RadzenDataGridColumn TItem="OrderDetail" Property="Id" Title="Product Number" Frozen="true" OrderIndex="1"/>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="ProductCode" Title="Code" Frozen="true" OrderIndex="2">
                                 <EditTemplate Context="orderDetail">
                                     <RadzenTextBox @bind-Value="orderDetail.ProductCode" Style="width: 100%; display: block" Name="ProductCode"/>
                                     <RadzenRequiredValidator Text="Product Code is required" Component="ProductCode" Popup="true" Style="position: absolute"/>
                                 </EditTemplate>
                             </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="ProductName" Title="Name" Frozen="true" OrderIndex="3">
                                 <EditTemplate Context="orderDetail">
                                     <RadzenTextBox @bind-Value="orderDetail.ProductName" Style="width: 100%; display: block" Name="ProductName"/>
                                     <RadzenRequiredValidator Text="Product Name is required" Component="ProductName" Popup="true" Style="position: absolute"/>
                                 </EditTemplate>
                             </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="Vendor.Name" Title="Vendor" Width="200px" OrderIndex="4">
                                 <EditTemplate Context="orderDetail">
                                     <RadzenDropDownDataGrid TValue="int"  AllowFiltering="true" AllowClear="true" FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive" FilterOperator="StringFilterOperator.Contains"
                                                             Data=@_vendors Count="5" TextProperty="Name" ValueProperty="Id"
                                                             Class="w-100" @bind-Value="orderDetail.VendorId"/>
                                        
                                 </EditTemplate>
                             </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="Currency" Title="Currency" OrderIndex="5">
                                 <EditTemplate Context="orderDetail">
                                    <RadzenDropDown AllowClear="true" TValue="string" Class="w-100" Data=@currency @bind-Value="orderDetail.Currency" Name="Currency" />
                                     <RadzenRequiredValidator Text="Currency is required" Component="Currency" Popup="true" Style="position: absolute"/>
                                 </EditTemplate>
                             </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="Quantity" Title="Quantity" OrderIndex="6">
                                 <EditTemplate Context="orderDetail">
                                     <RadzenNumeric TValue="int" Min="1" @bind-Value="orderDetail.Quantity" Style="width: 100%; display: block" Name="Quantity"/>
                                     <RadzenRequiredValidator Text="Quantity is required" Component="Quantity" Popup="true" Style="position: absolute"/>
                                 </EditTemplate>
                                 <FooterTemplate>
                                     <b>@string.Format(new CultureInfo("tr-TR"), "{0:G}", SelectedOrders?.FirstOrDefault()?.OrderDetails.Sum(o => o.Quantity))</b>
                                 </FooterTemplate>
                             </RadzenDataGridColumn>
                             @*<AuthorizeView Roles="Administrators"> *@
                                 <RadzenDataGridColumn TItem="OrderDetail" Property="BuyUnitPrice" Title="Buy Unit Price" OrderIndex="7">
                                 <Template Context="detail">
                                     @switch (detail.Currency)
                                     {
                                         case "Dolar":
                                             @string.Format(new CultureInfo("en-US"), "{0:C2}", detail.BuyUnitPrice)
                                             break;
                                         case "Euro":
                                             @string.Format(new CultureInfo("en-FR"), "{0:C2}", detail.BuyUnitPrice)
                                             break;
                                         default:
                                             @string.Format(new CultureInfo("tr-TR"), "{0:C2}", detail.BuyUnitPrice)
                                             break;
                                     }
                                 </Template>
                                 <EditTemplate Context="orderDetail">
                                     <RadzenNumeric TValue="double" Min="1" @bind-Value="orderDetail.BuyUnitPrice" Style="width: 100%; display: block" Name="BuyUnitPrice"/>
                                     <RadzenRequiredValidator Text="BuyUnitPrice is required" Component="BuyUnitPrice" Popup="true" Style="position: absolute"/>
                                 </EditTemplate>
                             </RadzenDataGridColumn>
                            @* </AuthorizeView>*@
                             <RadzenDataGridColumn TItem="OrderDetail" Property="TotalBuyPrice" Title="Total Buy" OrderIndex="8">
                                <Template Context="detail">
                                     @switch (detail.Currency)
                                     {
                                         case "Dolar":
                                             @string.Format(new CultureInfo("en-US"), "{0:C2}", detail.BuyUnitPrice * detail.Quantity)
                                             break;
                                         case "Euro":
                                             @string.Format(new CultureInfo("en-FR"), "{0:C2}", detail.BuyUnitPrice * detail.Quantity)
                                             break;
                                         default:
                                             @string.Format(new CultureInfo("tr-TR"), "{0:C2}", detail.BuyUnitPrice * detail.Quantity)
                                             break;
                                     }
                                 </Template>
                                 <FooterTemplate>
                                     @if(SelectedOrders?.FirstOrDefault()?.OrderDetails.GroupBy(x => x.Currency).Count() == 1)
                                     {
                                         @switch (SelectedOrders?.FirstOrDefault()?.OrderDetails.FirstOrDefault().Currency)
                                         {
                                             case "Dolar":
                                                 <b>@string.Format(new CultureInfo("tr-TR"), "{0:C2}", SelectedOrders?.FirstOrDefault()?.OrderDetails.Sum(o => o.TotalBuyPrice))</b>
                                                 break;
                                             case "Euro":
                                                 <b>@string.Format(new CultureInfo("en-FR"), "{0:C2}", SelectedOrders?.FirstOrDefault()?.OrderDetails.Sum(o => o.TotalBuyPrice))</b>
                                                 break;
                                             default:
                                                 <b>@string.Format(new CultureInfo("tr-TR"), "{0:C2}", SelectedOrders?.FirstOrDefault()?.OrderDetails.Sum(o => o.TotalBuyPrice))</b>
                                                 break;
                                         }
                                            
                                     }
                                 </FooterTemplate>
                             </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="CostRatio" Title="Cost Ratio" OrderIndex="9">
                                 <Template Context="detail">
                                     @string.Format(new CultureInfo("tr-TR"), "{0:D2}","%" + detail.CostRatio/100)
                                 </Template>
                                 <EditTemplate Context="orderDetail">
                                     <RadzenNumeric TValue="double" Min="1" @bind-Value="orderDetail.CostRatio" Style="width: 100%; display: block" Name="CostRatio"/>
                                     <RadzenRequiredValidator Text="Cost Ratio is required" Component="CostRatio" Popup="true" Style="position: absolute"/>
                                 </EditTemplate>
                             </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="UnitCost" Title="Unit Cost" OrderIndex="10">
                                 <Template Context="detail">
                                     @switch (detail.Currency)
                                     {
                                         case "Dolar":
                                             @string.Format(new CultureInfo("en-US"), "{0:C}", (detail.BuyUnitPrice * (detail.CostRatio / 100)) + detail.BuyUnitPrice)
                                             break;
                                         case "Euro":
                                             @string.Format(new CultureInfo("en-FR"), "{0:C}", (detail.BuyUnitPrice * (detail.CostRatio / 100)) + detail.BuyUnitPrice)
                                             break;
                                         default:
                                             @string.Format(new CultureInfo("tr-TR"), "{0:C}", (detail.BuyUnitPrice * (detail.CostRatio / 100)) + detail.BuyUnitPrice)
                                             break;
                                     }
                                 </Template>
                             </RadzenDataGridColumn>
                         <RadzenDataGridColumn TItem="OrderDetail" Property="TotalUnitCost" Title="Total Unit Cost" OrderIndex="11">
                             <Template Context="detail">
                                 @switch (detail.Currency)
                                 {
                                     case "Dolar":
                                         @string.Format(new CultureInfo("en-US"), "{0:C}", (detail.Quantity * detail.UnitCost))
                                         break;
                                     case "Euro":
                                         @string.Format(new CultureInfo("en-FR"), "{0:C}", (detail.Quantity * detail.UnitCost))
                                         break;
                                     default:
                                         @string.Format(new CultureInfo("tr-TR"), "{0:C}", (detail.Quantity * detail.UnitCost))
                                         break;
                                 }
                             </Template>
                         </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="SellUnitPrice" Title="Sell Unit Price" OrderIndex="12">
                                 <Template Context="detail">
                                     @switch (detail.Currency)
                                     {
                                         case "Dolar":
                                             @string.Format(new CultureInfo("en-US"), "{0:C2}", detail.SellUnitPrice)
                                             break;
                                         case "Euro":
                                             @string.Format(new CultureInfo("en-FR"), "{0:C2}", detail.SellUnitPrice)
                                             break;
                                         default:
                                             @string.Format(new CultureInfo("tr-TR"), "{0:C2}", detail.SellUnitPrice)
                                             break;
                                     }
                                 </Template>
                                 <EditTemplate Context="orderDetail">
                                     <RadzenNumeric TValue="double" Min="1" @bind-Value="orderDetail.SellUnitPrice" Style="width: 100%; display: block" Name="SellUnitPrice"/>
                                     <RadzenRequiredValidator Text="Sell Unit price is required" Component="SellUnitPrice" Popup="true" Style="position: absolute"/>
                                 </EditTemplate>
                             </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="TotalSellPrice" Title="Total Sell" OrderIndex="13">
                                 <Template Context="detail">
                                     @switch (detail.Currency)
                                     {
                                         case "Dolar":
                                             @string.Format(new CultureInfo("en-US"), "{0:C2}", detail.SellUnitPrice * detail.Quantity)
                                             break;
                                         case "Euro":
                                             @string.Format(new CultureInfo("en-FR"), "{0:C2}", detail.SellUnitPrice * detail.Quantity)
                                             break;
                                         default:
                                             @string.Format(new CultureInfo("tr-TR"), "{0:C2}", detail.SellUnitPrice * detail.Quantity)
                                             break;
                                     }
                                 </Template>
                                 <FooterTemplate>
                                     @if(SelectedOrders?.FirstOrDefault()?.OrderDetails.GroupBy(x => x.Currency).Count() == 1)
                                     {
                                         @switch (SelectedOrders?.FirstOrDefault()?.OrderDetails.FirstOrDefault().Currency)
                                         {
                                             case "Dolar":
                                                 <b>@string.Format(new CultureInfo("tr-TR"), "{0:C2}", SelectedOrders?.FirstOrDefault()?.OrderDetails.Sum(o => o.TotalSellPrice))</b>
                                                 break;
                                             case "Euro":
                                                 <b>@string.Format(new CultureInfo("en-FR"), "{0:C2}", SelectedOrders?.FirstOrDefault()?.OrderDetails.Sum(o => o.TotalSellPrice))</b>
                                                 break;
                                             default:
                                                 <b>@string.Format(new CultureInfo("tr-TR"), "{0:C2}", SelectedOrders?.FirstOrDefault()?.OrderDetails.Sum(o => o.TotalSellPrice))</b>
                                                 break;
                                         }
                                            
                                     }
                                 </FooterTemplate>
                             </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="ShippingNumber" Title="Shipment" OrderIndex="14">
                                 <EditTemplate Context="orderDetail">
                                     <RadzenTextBox @bind-Value="orderDetail.ShippingNumber" Style="width: 100%; display: block" Name="ShippingNumber"/>
                                     <RadzenRequiredValidator Text="Shipping Number is required" Component="ShippingNumber" Popup="true" Style="position: absolute"/>
                                 </EditTemplate>
                             </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="TrackingNumber" Title="Tracking Number" OrderIndex="15">
                                 <EditTemplate Context="orderDetail">
                                     <RadzenTextBox @bind-Value="orderDetail.TrackingNumber" Style="width: 100%; display: block" Name="TrackingNumber"/>
                                     <RadzenRequiredValidator Text="Tracking Number is required" Component="TrackingNumber" Popup="true" Style="position: absolute"/>
                                 </EditTemplate>
                             </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="Description" Title="Description" OrderIndex="16">
                                 <EditTemplate Context="orderDetail">
                                     <RadzenTextBox @bind-Value="orderDetail.Description" Style="width: 100%; display: block" Name="Description"/>
                                     <RadzenRequiredValidator Text="Description is required" Component="Description" Popup="true" Style="position: absolute"/>
                                 </EditTemplate>
                             </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="Status" Title="Status" OrderIndex="17">
                                 <EditTemplate Context="orderDetail">
                                     <RadzenDropDown AllowClear="true" TValue="string" Class="w-100" Data=@detailStatusList @bind-Value="orderDetail.Status" Name="Status" Change=@(args => OnChange(args, order.Id)) />
                                     <RadzenRequiredValidator Text="Status is required" Component="Status" Popup="true" Style="position: absolute"/>
                                 </EditTemplate>
                             </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="CustomerStockCode" Title="Customer Stock" OrderIndex="18">
                                 <EditTemplate Context="orderDetail">
                                     <RadzenTextBox @bind-Value="orderDetail.CustomerStockCode" Style="width: 100%; display: block" Name="CustomerStockCode"/>
                                     <RadzenRequiredValidator Text="Customer Stock Code is required" Component="CustomerStockCode" Popup="true" Style="position: absolute"/>
                                 </EditTemplate>
                             </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="CustomerOrderNumber" Title="Customer Order" OrderIndex="19">
                                 <EditTemplate Context="orderDetail">
                                     <RadzenTextBox @bind-Value="orderDetail.CustomerOrderNumber" Style="width: 100%; display: block" Name="CustomerOrderNumber"/>
                                     <RadzenRequiredValidator Text="Customer Order Number is required" Component="CustomerOrderNumber" Popup="true" Style="position: absolute" />
                                 </EditTemplate>
                             </RadzenDataGridColumn>
                             <RadzenDataGridColumn TItem="OrderDetail" Property="OrderId" Title="Order Id" OrderIndex="20"/>
                             <RadzenDataGridColumn TItem="OrderDetail" Context="orderDetail" Filterable="false" Sortable="false" TextAlign="TextAlign.Center" Width="200px" OrderIndex="20">
                                 <Template Context="detail">
                                     <RadzenButton Icon="edit" ButtonStyle="ButtonStyle.Primary" Class="m-1" Click="@(args => EditRowDetail(detail))" @onclick:stopPropagation="true">
                                     </RadzenButton>
                                 </Template>
                                 <EditTemplate Context="detail">
                                     <RadzenButton Icon="check" ButtonStyle="ButtonStyle.Primary" Class="m-1" Click="@(args => SaveRowDetail(detail))">
                                     </RadzenButton>
                                     <RadzenButton Icon="close" ButtonStyle="ButtonStyle.Light" Class="m-1" Click="@(args => CancelEditDetail(detail))">
                                     </RadzenButton>
                                     <RadzenButton Icon="delete" ButtonStyle="ButtonStyle.Danger" Class="m-1" Click="@(args => PassiveDetail(detail))">
                                     </RadzenButton>
                                 </EditTemplate>
                             </RadzenDataGridColumn>
                         </Columns>
                     </RadzenDataGrid>
                 </RadzenTabsItem>
    
             </Tabs>
         </RadzenTabs>
     </Template>
     <Columns>
         <RadzenDataGridColumn TItem="Order" Property="Id" Title="Order ID" Width="120px"/>
         <RadzenDataGridColumn TItem="Order" Property="Customer.Name" Title="Customer" Width="200px">
             <EditTemplate Context="order">
                 <RadzenDropDownDataGrid TValue="int"  AllowFiltering="true" AllowClear="true" FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive" FilterOperator="StringFilterOperator.Contains"
                                         Data=@_customers Count="5" TextProperty="Name" ValueProperty="Id"
                                         Class="w-100" @bind-Value="order.CustomerId"/>
                                        
             </EditTemplate>
         </RadzenDataGridColumn>
         <RadzenDataGridColumn TItem="Order" Property="OrderDateTime" Title="Order Date" Width="200px">
             <Template Context="order">
                 @($"{order.OrderDateTime:dd/MM/yyyy}")
             </Template>
             <EditTemplate Context="order">
                 <RadzenDatePicker @bind-Value="order.OrderDateTime" DateFormat="dd/MM/yyyy HH:mm" Class="w-100"/>
             </EditTemplate>
         </RadzenDataGridColumn>
         <RadzenDataGridColumn TItem="Order" Property="Status" Title="Status" Width="100px">
             @*<EditTemplate Context="order">
                    
                 <RadzenDropDown AllowClear="true" TValue="string" Class="w-150" Data=@orderStatusList Name="Status" @bind-Value="order.Status"/>
                 <RadzenRequiredValidator Text="Status is required" Component="Status" Popup="true" Style="position: absolute"/>
             </EditTemplate>*@
         </RadzenDataGridColumn>
         @*<RadzenDataGridColumn TItem="Order" Property="DoneBy" Title="Employee">
             <EditTemplate Context="order">
                 <RadzenTextBox @bind-Value="order.DoneBy" Style="width: 100%; display: block" Name="DoneBy"/>
                 <RadzenRequiredValidator Text="DoneBy is required" Component="DoneBy" Popup="true" Style="position: absolute"/>
             </EditTemplate>
         </RadzenDataGridColumn>*@
         <RadzenDataGridColumn TItem="Order" Context="order" Filterable="false" Sortable="false" TextAlign="TextAlign.Center" Width="120px">
             <Template Context="order">
                 <RadzenButton Icon="edit" ButtonStyle="ButtonStyle.Primary" Class="m-1" Click="@(args => EditRow(order))" @onclick:stopPropagation="true">
                 </RadzenButton>
             </Template>
             <EditTemplate Context="order">
                 <RadzenButton Icon="check" ButtonStyle="ButtonStyle.Primary" Class="m-1" Click="@(args => SaveRow(order))">
                 </RadzenButton>
                 <RadzenButton Icon="close" ButtonStyle="ButtonStyle.Light" Class="m-1" Click="@(args => CancelEdit(order))">
                 </RadzenButton>
             </EditTemplate>
         </RadzenDataGridColumn>
    
     </Columns>
 </RadzenDataGrid>
    
 @code {
     [Parameter]
     public bool DisplayAlert { get; set; } = false; 
     [Parameter]
     public string? SelectedStatus { get; set; }
    
     // Options to display in the roles dropdown when editing a user
     readonly List<string> detailStatusList = new() { "At customs", "Being supplied", "Cancelled", "Completed", "Getting ready", "In warehouse",  "Shipped" };
     readonly List<string> orderStatusList = new() { "Continues", "Cancelled", "Completed" };
     readonly List<string> currency = new() { "TL", "Dolar", "Euro"};
    
     IList<Order?> SelectedOrders { get; set; }
     IEnumerable<Order?> _orders = new List<Order?>();
     IEnumerable<Vendor?> _vendors;
     IEnumerable<Customer?> _customers;
     IQueryable<Order?> filter;
     IQueryable<OrderDetail?> filterDetail;
    
     RadzenDataGrid<Order?> _grid;
     RadzenDataGrid<OrderDetail> _gridDetail;
    
     Order? _orderToInsert;
     OrderDetail? _detailToInsert;
    
     ClaimsPrincipal user;
    
    
     protected override async Task OnInitializedAsync()
     {
         user = (await _authenticationStateProvider.GetAuthenticationStateAsync()).User;
    
         //userName = user.Identity.Name;
         if (!user.Identity.IsAuthenticated)
         {
             NavigationManager.NavigateTo("/Identity/Account/Login", false);
         }
         _orders = await ViewAllOrdersUseCase.ExecuteAsync(user);
         SelectedOrders = new List<Order?> { _orders.FirstOrDefault() };
         _vendors = await ViewAllVendorsUseCase.ExecuteAsync();
         _customers = await ViewAllCustomersUseCase.ExecuteAsync();
     }
    
    
     private void OnChange(object args, int id)
     {
         if(args != null){
             SelectedStatus = args.ToString();
         }
    
     }
    
     private async Task RowClick(DataGridRowMouseEventArgs<Order> mouseClick) {
    
         await _grid!.ExpandRow(mouseClick.Data);
    
     }
    
     private async Task InsertRow()
     {
         _orderToInsert = new Order
         {
             OrderDateTime = DateTime.Now,
             OrderDetails = new List<OrderDetail>()
         };
         await _grid.InsertRow(_orderToInsert);
     }
    
     private async Task InsertDetailRow(int id)
     {
         _detailToInsert = new OrderDetail
         {
             OrderId = id
         };
         await _gridDetail.InsertRow(_detailToInsert);
     }
    
     private async Task OnCreateRow(Order? order)
     {
         if (order != null)
         {
             await AddOrderUseCase.ExecuteAsync(order, user);
         }
     }
    
     private async Task OnCreateRowDetail(OrderDetail? orderDetail)
     {
         if (orderDetail != null)
         {
             await AddOrderDetailUseCase.ExecuteAsync(orderDetail);
         }
     }
    
     private async Task OnUpdateRow(Order order)
     {
         if (order == _orderToInsert)
         {
             _orderToInsert = null;
         }
    
         if (order != null)
         {
             await EditOrderUseCase.ExecuteAsync(order);
         }
     }
    
     private async Task OnUpdateRowDetail(OrderDetail orderDetail)
     {
         if (orderDetail == _detailToInsert)
         {
             _detailToInsert = null;
         }
         if (orderDetail != null)
         {
             await EditOrderDetailUseCase.ExecuteAsync(orderDetail);
         }
     }
    
     private void CancelEdit(Order? order)
     {
         if (order == _orderToInsert)
         {
             _orderToInsert = null;
         }
    
         _grid.CancelEditRow(order);
         CancelOrderUseCase.Execute(order);
     }
    
     private void CancelEditDetail(OrderDetail orderDetail)
     {
         if (orderDetail == _detailToInsert)
         {
             _detailToInsert = null;
         }
    
         _gridDetail.CancelEditRow(orderDetail);
         CancelOrderDetailUseCase.Execute(orderDetail);
     } 
    
     async Task EditRow(Order? order)
     {
         await _grid.EditRow(order);
     }
    
     async Task EditRowDetail(OrderDetail orderDetail)
     {
         await _gridDetail.EditRow(orderDetail);
     }
    
     async Task EditRowDetails(IList<OrderDetail?> SelectedOrders)
     {
         foreach (var detail in SelectedOrders)
         {
             await _gridDetail.EditRow(detail);
         }
     }
     private void CancelEdits(IList<OrderDetail?> SelectedOrders){
    
         foreach (var detail in SelectedOrders)
         {
             if (detail == _detailToInsert)
             {
                 _detailToInsert = null;
             }
    
             _gridDetail.CancelEditRow(detail);
             CancelOrderDetailUseCase.Execute(detail);
         }
     }
    
     async Task SaveRow(Order? order)
     {
         if (order == _orderToInsert)
         {
             _orderToInsert = null;
         }
    
         await _grid.UpdateRow(order);
    
         _orders = await ViewAllOrdersUseCase.ExecuteAsync(user);
         StateHasChanged();
         //DisplayAlert = true;
     }
    
    
     async Task SaveRowDetail(OrderDetail orderDetail)
     {
         if (orderDetail == _detailToInsert)
         {
             _detailToInsert = null;
         }
    
         await _gridDetail.UpdateRow(orderDetail);
    
         if(SelectedStatus != null && (SelectedStatus.ToString() == "Completed" || SelectedStatus.ToString() == "Cancelled")){
             var order = await ViewOrdersByStatusUseCase.ExecuteAsync(SelectedStatus.ToString(), orderDetail.OrderId);
             if (order != null)
             {
                 order.Status = SelectedStatus.ToString();
                 await EditOrderUseCase.ExecuteAsync(order);
             }
         }
     }
     async Task PassiveDetail(OrderDetail orderDetail)
     {
         if (orderDetail == _detailToInsert)
         {
             _detailToInsert = null;
         }
    
         await _gridDetail.UpdateRow(orderDetail);
         await PassiveOrderDetailUseCase.ExecuteAsync(orderDetail);
            
         _orders = await ViewAllOrdersUseCase.ExecuteAsync(user);
         StateHasChanged();
    
     }
     async Task SaveRowDetails(IList<OrderDetail?> SelectedOrders)
     {
         var id = 0;
         foreach (var detail in SelectedOrders)
         {
             id = detail.OrderId;
             if (detail == _detailToInsert)
             {
                 _detailToInsert = null;
             }
    
             await _gridDetail.UpdateRow(detail);
         }
         if(SelectedStatus != null && (SelectedStatus.ToString() == "Completed" || SelectedStatus.ToString() == "Cancelled")){
             var order = await ViewOrdersByStatusUseCase.ExecuteAsync(SelectedStatus.ToString(), id);
             if (order != null)
             {
                 order.Status = SelectedStatus.ToString();
                 await EditOrderUseCase.ExecuteAsync(order);
             }
         }
     }
     private async Task ExportExcel()
     {
         filter = _grid.View;
         //var vCount = _gridDetail.View.Count();
         //var dCount = _gridDetail.Data.Count();
         //List<OrderDetail?> od = null;
    
         //filterDetail = _gridDetail.View;
    
         ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
         var stream = new MemoryStream();
    
         using (var package = new ExcelPackage(stream))
         {
             var workSheet = package.Workbook.Worksheets.Add("Orders");
    
             var recordIndex = 2;
    
             workSheet.Row(1).Style.Font.Bold = true;
             var headerCells = workSheet.Cells["A1:U1"];
             headerCells.Style.Font.Bold = true;
             headerCells.Style.Font.Size = 13;
             headerCells.Style.Border.BorderAround(ExcelBorderStyle.Thin);
             headerCells.Style.Border.Top.Style = ExcelBorderStyle.Thin;
             headerCells.Style.Border.Left.Style = ExcelBorderStyle.Thin;
             headerCells.Style.Border.Right.Style = ExcelBorderStyle.Thin;
             headerCells.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
             headerCells.Style.Font.Color.SetColor(System.Drawing.Color.Black);
             headerCells = workSheet.Cells["A1:E1"];
             // Set their background color to DarkBlue.
             headerCells.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
             headerCells.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
             headerCells = workSheet.Cells["F1:U1"];
             // Set their background color to DarkBlue.
             headerCells.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
             headerCells.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightBlue);
             workSheet.Cells[1, 1].Value = "Order Id";
             workSheet.Cells[1, 2].Value = "Order Date";
             workSheet.Cells[1, 3].Value = "Status";
             workSheet.Cells[1, 4].Value = "Customer";
             workSheet.Cells[1, 5].Value = "DoneBy";
             workSheet.Cells[1, 6].Value = "ID";
             workSheet.Cells[1, 7].Value = "Product Code";
             workSheet.Cells[1, 8].Value = "Product";
             workSheet.Cells[1, 9].Value = "Vendor";
             workSheet.Cells[1, 10].Value = "Quantity";
             workSheet.Cells[1, 11].Value = "Cost Ratio";
             workSheet.Cells[1, 12].Value = "Currency";
             workSheet.Cells[1, 13].Value = "Unit Cost";
             workSheet.Cells[1, 14].Value = "Buy Unit Price";
             workSheet.Cells[1, 15].Value = "Total Buy Price";
             workSheet.Cells[1, 16].Value = "Sell Unit Price";
             workSheet.Cells[1, 17].Value = "Total Sell Price";
             workSheet.Cells[1, 18].Value = "Status";
             workSheet.Cells[1, 19].Value = "Shipping Number";
             workSheet.Cells[1, 20].Value = "Tracking Number";
             workSheet.Cells[1, 21].Value = "Description";
    
    
             foreach (var order in filter)
             {
                 workSheet.Cells[recordIndex, 1].Value = order.Id;
                 workSheet.Cells[recordIndex, 1].Style.Font.Bold = true;
                 workSheet.Cells[recordIndex, 2].Value = order.OrderDateTime.ToShortDateString();
                 workSheet.Cells[recordIndex, 3].Value = order.Status;
                 workSheet.Cells[recordIndex, 4].Value = order.Customer.Name;
                 workSheet.Cells[recordIndex, 5].Value = order.DoneBy;
                 var quantity = 0;
    
                 //var totalBuy = 0.0;
                 //var totalSell = 0.0;
    
    
                 foreach (var orderDetails in order.OrderDetails)
                 {
    
                     workSheet.Cells[recordIndex, 6].Value = orderDetails.Id;
                     workSheet.Cells[recordIndex, 6].Style.Font.Bold = true;
                     workSheet.Cells[recordIndex, 7].Value = orderDetails.ProductCode;
                     workSheet.Cells[recordIndex, 8].Value = orderDetails.ProductName;
                     workSheet.Cells[recordIndex, 9].Value = orderDetails.Vendor.Name;
                     workSheet.Cells[recordIndex, 10].Value = orderDetails.Quantity;
                     workSheet.Cells[recordIndex, 11].Value = orderDetails.CostRatio;
                     workSheet.Cells[recordIndex, 12].Value = orderDetails.Currency;
                     workSheet.Cells[recordIndex, 13].Value = (orderDetails.BuyUnitPrice * (orderDetails.CostRatio/100)) + orderDetails.BuyUnitPrice;
                     workSheet.Cells[recordIndex, 14].Value = orderDetails.BuyUnitPrice;
                     workSheet.Cells[recordIndex, 15].Value = orderDetails.BuyUnitPrice * orderDetails.Quantity;
                     workSheet.Cells[recordIndex, 16].Value = orderDetails.SellUnitPrice;
                     workSheet.Cells[recordIndex, 17].Value = orderDetails.Quantity * orderDetails.SellUnitPrice;
                     workSheet.Cells[recordIndex, 18].Value = orderDetails.Status;
                     workSheet.Cells[recordIndex, 19].Value = orderDetails.ShippingNumber;
                     workSheet.Cells[recordIndex, 20].Value = orderDetails.TrackingNumber;
                     workSheet.Cells[recordIndex, 21].Value = orderDetails.Description;
    
                     quantity += orderDetails.Quantity;
                     //totalBuy += orderDetails.TotalBuyPrice;
                     //totalSell += orderDetails.TotalSellPrice;
    
                     recordIndex++;
                 }
                 workSheet.Cells[recordIndex, 1].Value = "Total:";
                 workSheet.Cells["A" + recordIndex + ":U" + recordIndex].Style.Border.Top.Style = ExcelBorderStyle.Thin;
                 workSheet.Cells["A" + recordIndex + ":U" + recordIndex].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                 workSheet.Cells["A" + recordIndex + ":U" + recordIndex].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Yellow);
                 workSheet.Cells[recordIndex, 10].Value = quantity;
                 workSheet.Cells[recordIndex, 10].Style.Font.Bold = true;
                 workSheet.Cells[recordIndex, 10].Style.Font.Size = 11;
                 //workSheet.Cells[recordIndex, 15].Value = totalBuy;
                 //workSheet.Cells[recordIndex, 15].Style.Font.Bold = true;
                 //workSheet.Cells[recordIndex, 15].Style.Font.Size = 11;
                 //workSheet.Cells[recordIndex, 17].Value = totalSell;
                 //workSheet.Cells[recordIndex, 17].Style.Font.Bold = true;
                 //workSheet.Cells[recordIndex, 17].Style.Font.Size = 11;
    
                 recordIndex++;
             }
    
    
             //Make all text fit the cells
             workSheet.Cells[workSheet.Dimension.Address].AutoFitColumns();
             await package.SaveAsync();
         }
         stream.Position = 0;
         var excelName = $"OrderList-{DateTime.Now.ToString("ddMMyyyyHHmm")}.xlsx";
    
    
         using var streamRef = new DotNetStreamReference(stream: stream);
    
         await JS.InvokeVoidAsync("downloadFileFromStream", excelName, streamRef);
     }
    
     private async Task ExportDetailExcel()
     {
         filterDetail = _gridDetail.View;
    
         ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
         var stream = new MemoryStream();
    
         using (var package = new ExcelPackage(stream))
         {
             var workSheet = package.Workbook.Worksheets.Add("Orders");
    
             var recordIndex = 2;
    
             workSheet.Row(1).Style.Font.Bold = true;
             var headerCells = workSheet.Cells["A1:U1"];
             headerCells.Style.Font.Bold = true;
             headerCells.Style.Font.Size = 13;
             headerCells.Style.Border.BorderAround(ExcelBorderStyle.Thin);
             headerCells.Style.Border.Top.Style = ExcelBorderStyle.Thin;
             headerCells.Style.Border.Left.Style = ExcelBorderStyle.Thin;
             headerCells.Style.Border.Right.Style = ExcelBorderStyle.Thin;
             headerCells.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
             headerCells.Style.Font.Color.SetColor(System.Drawing.Color.Black);
             headerCells = workSheet.Cells["A1:E1"];
             // Set their background color to DarkBlue.
             headerCells.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
             headerCells.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
             headerCells = workSheet.Cells["F1:U1"];
             // Set their background color to DarkBlue.
             headerCells.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
             headerCells.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightBlue);
             workSheet.Cells[1, 1].Value = "Order Id";
             workSheet.Cells[1, 2].Value = "Order Date";
             workSheet.Cells[1, 3].Value = "Status";
             workSheet.Cells[1, 4].Value = "Customer";
             workSheet.Cells[1, 5].Value = "DoneBy";
             workSheet.Cells[1, 6].Value = "ID";
             workSheet.Cells[1, 7].Value = "Product Code";
             workSheet.Cells[1, 8].Value = "Product";
             workSheet.Cells[1, 9].Value = "Vendor";
             workSheet.Cells[1, 10].Value = "Quantity";
             workSheet.Cells[1, 11].Value = "Cost Ratio";
             workSheet.Cells[1, 12].Value = "Currency";
             workSheet.Cells[1, 13].Value = "Unit Cost";
             workSheet.Cells[1, 14].Value = "Buy Unit Price";
             workSheet.Cells[1, 15].Value = "Total Buy Price";
             workSheet.Cells[1, 16].Value = "Sell Unit Price";
             workSheet.Cells[1, 17].Value = "Total Sell Price";
             workSheet.Cells[1, 18].Value = "Status";
             workSheet.Cells[1, 19].Value = "Shipping Number";
             workSheet.Cells[1, 20].Value = "Tracking Number";
             workSheet.Cells[1, 21].Value = "Description";
    
             var i = 1;
             var quantity = 0;
    
             foreach (var order in filterDetail)
             {
                 if(i == 1){
                     workSheet.Cells[recordIndex, 1].Value = order.OrderId;
                     workSheet.Cells[recordIndex, 1].Style.Font.Bold = true;
                     workSheet.Cells[recordIndex, 2].Value = order.Order.OrderDateTime.ToShortDateString();
                     workSheet.Cells[recordIndex, 3].Value = order.Status;
                     workSheet.Cells[recordIndex, 4].Value = order.Order.Customer.Name;
                     workSheet.Cells[recordIndex, 5].Value = order.Order.DoneBy;
                 }
                 i++;
                    
    
    
                 workSheet.Cells[recordIndex, 6].Value = order.Id;
                 workSheet.Cells[recordIndex, 6].Style.Font.Bold = true;
                 workSheet.Cells[recordIndex, 7].Value = order.ProductCode;
                 workSheet.Cells[recordIndex, 8].Value = order.ProductName;
                 workSheet.Cells[recordIndex, 9].Value = order.Vendor.Name;
                 workSheet.Cells[recordIndex, 10].Value = order.Quantity;
                 workSheet.Cells[recordIndex, 11].Value = order.CostRatio;
                 workSheet.Cells[recordIndex, 12].Value = order.Currency;
                 workSheet.Cells[recordIndex, 13].Value = (order.BuyUnitPrice * (order.CostRatio / 100)) + order.BuyUnitPrice;
                 workSheet.Cells[recordIndex, 14].Value = order.BuyUnitPrice;
                 workSheet.Cells[recordIndex, 15].Value = order.BuyUnitPrice * order.Quantity;
                 workSheet.Cells[recordIndex, 16].Value = order.SellUnitPrice;
                 workSheet.Cells[recordIndex, 17].Value = order.Quantity * order.SellUnitPrice;
                 workSheet.Cells[recordIndex, 18].Value = order.Status;
                 workSheet.Cells[recordIndex, 19].Value = order.ShippingNumber;
                 workSheet.Cells[recordIndex, 20].Value = order.TrackingNumber;
                 workSheet.Cells[recordIndex, 21].Value = order.Description;
    
                 quantity += order.Quantity;
                    
                 recordIndex++;
             }
             workSheet.Cells[recordIndex, 1].Value = "Total:";
             workSheet.Cells["A" + recordIndex + ":U" + recordIndex].Style.Border.Top.Style = ExcelBorderStyle.Thin;
             workSheet.Cells["A" + recordIndex + ":U" + recordIndex].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
             workSheet.Cells["A" + recordIndex + ":U" + recordIndex].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Yellow);
             workSheet.Cells[recordIndex, 10].Value = quantity;
             workSheet.Cells[recordIndex, 10].Style.Font.Bold = true;
             workSheet.Cells[recordIndex, 10].Style.Font.Size = 11;
    
     //Make all text fit the cells
             workSheet.Cells[workSheet.Dimension.Address].AutoFitColumns();
             await package.SaveAsync();
         }
         stream.Position = 0;
         var excelName = $"OrderList-{DateTime.Now.ToString("ddMMyyyyHHmm")}.xlsx";
    
    
         using var streamRef = new DotNetStreamReference(stream: stream);
    
         await JS.InvokeVoidAsync("downloadFileFromStream", excelName, streamRef);
     }
        
            
           
 }



5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Cenk-1028 avatar image
0 Votes"
Cenk-1028 answered

They are in different repositories, is it because of this? I mean something to mark as modified or something.

Order Repository

 namespace IMS.Plugins.EFCore
 {
     public class OrderRepository : IOrderRepository
     {
         private readonly IMSContext _db;
            
         public OrderRepository(IMSContext db)
         {
             _db = db;
               
         }
    
         public async Task<IEnumerable<Order?>> GetAllOrders(ClaimsPrincipal user)
         {
             if (user.IsInRole("Administrators"))
             {
                 return await _db.Orders.Include(d => d.OrderDetails.Where(od => od.IsActive == 1)).ThenInclude(v => v.Vendor).ToListAsync();
             }
                
             return await _db.Orders.Include(d => d.OrderDetails.Where(od => od.IsActive == 1)).ThenInclude(v => v.Vendor).ToListAsync();
    
         }
    
            
    
           
     }
 }

Order Detail Repository

 namespace IMS.Plugins.EFCore
 {
     public class OrderDetailRepository : IOrderDetailRepository
     {
         private readonly IMSContext _db;
    
         public OrderDetailRepository(IMSContext db)
         {
             _db = db;
         }
    
    
         public async Task PassiveOrderDetailAsync(OrderDetail orderDetail)
         {
               
             var detail = await this._db.OrdersDetail.FindAsync(orderDetail.Id);
             if (detail != null)
             {
                    
                 detail.IsActive = 0; // 0-Passive
                    
                 await _db.SaveChangesAsync();
             }
         }
           
     }
 }

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Cenk-1028 avatar image
0 Votes"
Cenk-1028 answered Cenk-1028 commented

It seems that this problem occurs because they are different repositories. I tried something like this in the Order Detail repository.

 public async Task<IEnumerable<OrderDetail>> GetOrderDetailsByOrderId(int orderId)
         {
             return await _db.OrdersDetail
                 .Where(x => x.OrderId == orderId && x.IsActive == 1)
                 .OrderBy(x => x.VendorId).ToListAsync();
         }

And on the Blazor page, I tried something like this and this time the query below gets only the active ones.

 async Task PassiveDetail(OrderDetail orderDetail)
     {
         if (orderDetail == _detailToInsert)
         {
             _detailToInsert = null;
         }
    
    
         await _gridDetail.UpdateRow(orderDetail);
    
         await PassiveOrderDetailUseCase.ExecuteAsync(orderDetail);
            
         var _ordersdetails = await ViewOrderDetailsByOrderIdUseCase.ExecuteAsync(orderDetail.OrderId); //gets  only the active ones
    
         StateHasChanged();
            
    
     }

So the question is how I can make this work. Somehow replacing the order detail with LINQ or when I save changes of the order details in the repository, should I also add this order detail to the orders and save the orders? Any ideas?

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @Cenk-1028,

       await _gridDetail.UpdateRow(orderDetail);    
         await PassiveOrderDetailUseCase.ExecuteAsync(orderDetail);            
         var _ordersdetails = await ViewOrderDetailsByOrderIdUseCase.ExecuteAsync(orderDetail.OrderId); //gets  only the active ones

In your description, we only know you are using the above method to update the order detail, but not sure the detailed update command, so we are not sure whether the issue relates it or not.

And you are using the order repository and order detail repository to query data, the only difference between them is that in the order details repository, it will update the IsActive, are you sure the issue relates to this?

Since I still have doubts about your question, I only suggest that you set breakpoints in these methods or Linq commands to track data state.

Best regards,
Dillion

0 Votes 0 ·

Is it due to the loading of related data? I am using EF Core 6.

0 Votes 0 ·
Cenk-1028 avatar image
0 Votes"
Cenk-1028 answered Cenk-1028 commented

I think I found the suspect. The query below shouldn't get the IsActive=0 but it somehow gets! Any ideas for this situation?

Here is the query:

 public async Task<IEnumerable<Order?>> GetAllOrders(ClaimsPrincipal user)
     {
         if (user.IsInRole("Administrators"))
         {
             return await _db.Orders.Include(d => d.OrderDetails.Where(od => od.IsActive == 1)).ThenInclude(v => v.Vendor).ToListAsync();
         }
            
         return await _db.Orders.Include(d => d.OrderDetails.Where(od => od.IsActive == 1)).ThenInclude(v => v.Vendor).ToListAsync();
    
     }

The record is updated, why is the query doesn't work the way it is expected? First I am updating then I am querying IsActive = 1

 await PassiveOrderDetailUseCase.ExecuteAsync(orderDetail); //sets to IsActive = 0
 _orders = await ViewAllOrdersUseCase.ExecuteAsync(user); // call GetAllOrders method above, should get only the actives IsActive = 1


But IsActive = 0 also comes inside of _orders as seen in the screenshot below.
242621-isactive.png








isactive.png (88.2 KiB)
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

The LINQ query in the GetAllOrders() method is not filtered by user but the PassiveDetials fetches records by user. I assume this is where the design bug is located but you have not provided enough code. We can only guess what is going on in your code.

Also the GetAllOrders() returns the same records regardless of the role which is a bit odd.

0 Votes 0 ·

It is not the case even though I fixed the query GetAllOrders gets all of the records even if it is IsActive = 0

242766-0.png



Fixed query if you want to see:

 public async Task<IEnumerable<Order?>> GetAllOrders(ClaimsPrincipal user)
         {
             if (user.IsInRole("Administrators"))
             {
                 return await _db.Orders.Include(d => d.OrderDetails.Where(od => od.IsActive == 1)).ThenInclude(v => v.Vendor).ToListAsync();
             }
                
             return await _db.Orders.Where(u => u.DoneBy == user.Identity.Name).Include(d => d.OrderDetails.Where(od => od.IsActive == 1)).ThenInclude(v => v.Vendor).ToListAsync();
    
         }


0 Votes 0 ·
0.png (33.4 KiB)
Cenk-1028 avatar image
0 Votes"
Cenk-1028 answered AgaveJoe edited

@ZhiLv-MSFT do you have a solution for this issue? Why the query gets IsActive = 0?

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

do you have a solution for this issue? Why the query gets IsActive = 0?

The problem you are facing is your code is functioning exactly how you designed it to function but the results are not what you expect. It is up to you to troubleshoot your code!

We cannot run your code and you refuse to share the relevant bits so we cannot review the code. It seems to me the ExecuteAsync() methods do not function as you expect or the data is set correctly but your UI is not refreshing the content. Set a break point and debug your code.

0 Votes 0 ·
Cenk-1028 avatar image
0 Votes"
Cenk-1028 answered Cenk-1028 commented

We cannot run your code and you refuse to share the relevant bits so we cannot review the code. It seems to me the ExecuteAsync() methods do not function as you expect or the data is set correctly but your UI is not refreshing the content.

Here is the ExecuteAsync for getting data:

 public class ViewAllOrdersUseCase : IViewAllOrdersUseCase
     {
         private readonly IOrderRepository _orderRepository;
    
         public ViewAllOrdersUseCase(IOrderRepository orderRepository)
         {
             _orderRepository = orderRepository;
         }
         public async Task<IEnumerable<Order?>> ExecuteAsync(ClaimsPrincipal user)
         {
             return await _orderRepository.GetAllOrders(user);
         }
     }

Here is ExecuteAsync for updating:

 public class PassiveOrderDetailUseCase : IPassiveOrderDetailUseCase
     {
         private readonly IOrderDetailRepository _orderDetailRepository;
    
         public PassiveOrderDetailUseCase(IOrderDetailRepository orderDetailRepository)
         {
             _orderDetailRepository = orderDetailRepository;
         }
    
         public async Task ExecuteAsync(OrderDetail orderDetail)
         {
             await _orderDetailRepository.PassiveOrderDetailAsync(orderDetail);
         }
     }

top secret codes are revealed as you wish :)

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I'm a little confused as you still did not share the relevant code. Please set a break point and debug your repository design. If the repositories are functioning as expected then the problem could be in the UI.

0 Votes 0 ·

Is it due to the loading of related data?

0 Votes 0 ·
Cenk-1028 avatar image
0 Votes"
Cenk-1028 answered

Seems like the loading of related data. How to add Customer to this linq? Couldn't manage.

 public class Order
     {
         public int Id { get; set; }
            
         [Required]
         public DateTime OrderDateTime { get; set; }
         [Required]
         [MaxLength(250)]
         public int CustomerId { get; set; }
         public string Status { get; set; }
         [MaxLength(50)]
         public string DoneBy { get; set; }
         public List<OrderDetail> OrderDetails { get; set; }
         public Customer Customer { get; set; }
    
    
     }
 public class OrderDetail
     {
         public int Id { get; set; }
            
         [Required]
         [MaxLength(100)]
         public string ProductCode { get; set; }
         [Required]
         [MaxLength(250)]
         public string ProductName { get; set; }
         [Required]
         public int Quantity { get; set; }
         [Required]
         public double BuyUnitPrice { get; set; }
         public double CostRatio { get; set; }
         public double UnitCost { get; set; }
         public double TotalBuyPrice { get; set; }
         public double? SellUnitPrice { get; set; }
         public double? TotalSellPrice { get; set; }
         [MaxLength(150)]
         public string? ShippingNumber { get; set; }
         public string? Status { get; set; }
         [MaxLength(150)]
         public string? TrackingNumber { get; set; }
         [MaxLength(400)]
         public string? Description { get; set; }
         public string? Currency { get; set; }
         public string? CustomerStockCode { get; set; }
         public string? CustomerOrderNumber { get; set; }
         public int IsActive { get; set; }
         public double? TotalUnitCost { get; set; }
         public int OrderId { get; set; }
         public int VendorId { get; set; }
         public Order Order { get; set; }
         public Vendor Vendor { get; set; }
          
     }
 public class Customer
     {
         public int Id { get; set; }
         [Required]
         public long TaxNumber { get; set; }
         [Required]
         public string TaxAdministration { get; set; }
         [Required]
         public string Name { get; set; }
         [Required]
         public string Address { get; set; }
         [Required]
         public string DeliveryAddress { get; set; }
         [Required]
         [RegularExpression(@"^((?!\.)[\w-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$", ErrorMessage = "Invalid email address.")]
         public string Email { get; set; }
         [Required]
         public string PhoneNumber { get; set; }
         [Required]
         public string MainResponsibleName { get; set; }
         public string AssistantResponsibleName { get; set; }
     }
 public class Vendor
     {
         public int Id { get; set; }
         [Required]
         public string Name { get; set; }
         [Required]
         public string Address { get; set; }
         [Required]
         [RegularExpression(@"^((?!\.)[\w-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$", ErrorMessage = "Invalid email address.")]
         public string Email { get; set; }
         [Required]
         public string PhoneNumber { get; set; }
         [Required]
         public string MainResponsibleName { get; set; }
         public string AssistantResponsibleName { get; set; }
        public List<OrderDetail> OrderDetails { get; set; }
    
     }
    
 Linq:
 return await _db.Orders
                     .Include(d => d.OrderDetails.Where(od => od.IsActive == 1))
                     .ThenInclude(v => v.Vendor)
                     .AsNoTracking()
                     .ToListAsync();



5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Cenk-1028 avatar image
0 Votes"
Cenk-1028 answered Cenk-1028 commented

Hi @ZhiLv-MSFT,

When I add AsNoTracking() the query in my previous post gets only IsActive = 1 that is what I want but somehow doesn't get the Customer which is why I want to include it. Order have 2 children, Customer and OrderDetail. OrderDetail has one, Vendor. Couldn't manage to include Customer tough to the query.








· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @Cenk-1028,

   _db.Orders.Include(d => d.OrderDetails.Where(od => od.IsActive == 1)).ThenInclude(v => v.Vendor).ToListAsync(); 

From your description, do you mean the issue still relate the above query statement, sometimes it returns the correct data, but sometime the filter (IsActive) don't work?
If that is the case, the issue might relate the cache or the Linq statement.
I suggest you could try to use the following methods:

  1. Define a variable to store the query result. You can set a break point to check the value.

       public async Task<IEnumerable<Order?>> GetAllOrders(ClaimsPrincipal user)
              {
                  if (user.IsInRole("Administrators"))
                  {
                      var result1 = await _db.Orders.Include(d => d.OrderDetails.Where(od => od.IsActive == 1)).ThenInclude(v => v.Vendor).ToListAsync();
                      return result1;
                  }
                  var result2 = await _db.Orders.Where(u => u.DoneBy == user.Identity.Name).Include(d => d.OrderDetails.Where(od => od.IsActive == 1)).ThenInclude(v => v.Vendor).ToListAsync();
                  return result2; 
              }
    
  2. If the above method still not working, try to use FromSqlRaw() method to execute the SQL commands. More details, see Raw SQL Queries.

0 Votes 0 ·

From your description, do you mean the issue still relate the above query statement, sometimes it returns the correct data, but sometime the filter (IsActive) don't work?

I thought it was due to loading related data so added AsNoTracking to the query below. IsActive problem solved but different problems arose. After adding new order detail and trying to edit this new record, query didn't get this new added record because of No tracking I think. So I will try to do what you have suggested.

 await _db.Orders
                      .Include(d => d.OrderDetails.Where(od => od.IsActive == 1))
                      .ThenInclude(v => v.Vendor)
                      .AsNoTracking()
                      .ToListAsync();









0 Votes 0 ·

Couldn't manage to include Customer tough to the query.

For this issue, it still need to use a Include method, like this:

  _db.Orders.Include(d => d.OrderDetails.Where(od => od.IsActive == 1)).ThenInclude(v => v.Vendor).Include(c => c.Customer).ToListAsync(); 
0 Votes 0 ·
Cenk-1028 avatar image
0 Votes"
Cenk-1028 answered

I gave up using raw SQL because I had to change too many things on the page.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.