SELECT
Id,
No,
NetAmount,
PaidAmount,
NetAmount - PaidAmount AS AmountToBePayed
FROM
(
SELECT
m.Id,
m.No,
SUM(NetAmount) as NetAmount,
(
SELECT
COALESCE( SUM( PaidAmount ), 0 )
FROM
A_Account_Payable_Payment_Invoice
) as PaidAmount
FROM
A_Account_Payable_Invoice_M m
INNER JOIN A_Account_Payable_Invoice_Item d ON
m.Id = d.A_Account_Payable_Invoice
GROUP BY
m.Id,
m.No
) a
How can i use this query directly in LINQ C#
As you mentioned on comment section you don't want to translate SQL to LINQ, you just want to directly run this script.
To do so first you need to create class that will match with your Script like:
[DataContract()]
public class PaymentInvoiceResult
{
[DataMember]
public int Id { get; set; }
[DataMember]
public int No { get; set; }
[DataMember]
public int NetAmount { get; set; }
[DataMember]
public int PaidAmount { get; set; }
[DataMember]
public int AmountToBePayed { get; set; }
}
Then you need to use SqlQuery as following:
List<PaymentInvoiceResult> paymentInvoiceResultList = db.Database.SqlQuery<PaymentInvoiceResult>("Your Script").ToList();
You can simply use:
var results = db.ExecuteQuery(typeof(DTO), "sql query ");
Your dto should have members:
Id,
No,
NetAmount,
PaidAmount,
NetAmount - PaidAmount AS AmountToBePayed
Related
I need your help. I have a store procedure that executes perfectly in SQL but when I call her from an IActionResult from a .net controller with FromSqlRaw(), returns the following error :
System.InvalidOperationException: 'The required column 'SeasonGroupClientCode' was not present in the results of a 'FromSql' operation.'
in Action:
var sql = "EXECUTE sp_seasonDataGroupedHorizonatlallyByCompany";
var list = _context.SeasonGroupedByCompanies.FromSqlRaw(sql).AsNoTracking().ToList();
Store Procedure:
select * from
(SELECT [SeasonGroupSeasonDescription] AS FirstSeason,[SeasonGroupClientCode] AS
FirstSeasonClientCode,[SeasonGroupClientName] AS
FistSeasonClientName,SeasonGroupCompanyId],
SUM([SeasonGroupStartValue]) AS FiSTotalStartValue ,
SUM([SeasonGroupFinalValue]) AS FiSTotalFinalValue
FROM [dbo].[SeasonGroupedByCompanies]
WHERE [SeasonGroupSeasonDescription]='SS21'
GROUP BY [SeasonGroupClientCode],[SeasonGroupClientName],
[SeasonGroupSeasonDescription],[SeasonGroupCompanyId]) as td
full join
(SELECT [SeasonGroupSeasonDescription] AS SecondSeason,[SeasonGroupClientCode] AS
SecondSeasonClientCode,[SeasonGroupClientName] AS SecondSeasonClientName,
[SeasonGroupCompanyId] AS SecondId,
SUM([SeasonGroupStartValue]) AS SeSTotalStartValue ,
SUM([SeasonGroupFinalValue]) AS SeSTotalFinalValue
FROM [dbo].[SeasonGroupedByCompanies]
WHERE [SeasonGroupSeasonDescription]='FW21'
GROUP BY [SeasonGroupClientCode],[SeasonGroupClientName],[SeasonGroupSeasonDescription],
[SeasonGroupCompanyId]) as tf
on td.FistSeasonClientName = tf.SecondSeasonClientName
full join
(SELECT [SeasonGroupSeasonDescription] AS ThirdSeason,[SeasonGroupClientCode] AS
ThirdSeasonClientCode,[SeasonGroupClientName] AS ThirdSeasonClientName,
[SeasonGroupCompanyId] AS ThirdId,
SUM([SeasonGroupStartValue]) AS ThSTotalStartValue ,
SUM([SeasonGroupFinalValue]) AS ThSTotalFinalValue
FROM [dbo].[SeasonGroupedByCompanies]
WHERE [SeasonGroupSeasonDescription]='SS22'
GROUP BY [SeasonGroupClientCode],[SeasonGroupClientName],[SeasonGroupSeasonDescription],
[SeasonGroupCompanyId]) as ts
on td.FistSeasonClientName = ts.ThirdSeasonClientName
full join
(SELECT [SeasonGroupSeasonDescription] AS FourthSeason,[SeasonGroupClientCode]AS
FourthSeasonClientCode,[SeasonGroupClientName] AS FourthSeasonClientName,
[SeasonGroupCompanyId] AS FourthId,
SUM([SeasonGroupStartValue]) AS FoSTotalStartValue ,
SUM([SeasonGroupFinalValue]) AS FoSTtotalFinalValue
FROM [dbo].[SeasonGroupedByCompanies]
WHERE [SeasonGroupSeasonDescription]='FW22'
GROUP BY [SeasonGroupClientCode],[SeasonGroupClientName],[SeasonGroupSeasonDescription],
[SeasonGroupCompanyId]) as tx
on td.FistSeasonClientName = tx.FourthSeasonClientName
Entity
public class SeasonGroupByCompany
{
[Key]
public int SeasonGroupCompanyId { get; set; }
public string? SeasonGroupSeasonDescription { get; set; }
public string? SeasonGroupSalesman { get; set; }
public int SeasonGroupClientCode { get; set; }
public string? SeasonGroupClientName { get; set; }
public int SeasonGroupQuantity { get; set; }
public int SeasonGroupDiscount { get; set; }
public double SeasonGroupStartValue { get; set; }
public double SeasonGroupFinalValue { get; set; }
The same error comes up, even if I run the query directly from FromRawSql().
Thanks in advance, any help will be appreciated
It looks like in the SeasonGroupedByCompany entity you have a field named SeasonGroupClientCode, but in the SQL query you have renamed it into FirstSeasonClientCode:
...[SeasonGroupClientCode] AS FirstSeasonClientCode...
Either rename the field in the entity, or don't rename the column in SQL, because originally the naming looks to be consistent.
I have a get route a that is going to get data of wells and well tests, when I execute the call on swagger, it will take awhile and then give me a call stack error. My problem is I cant figure out how to get a log or idea of where this is happening. The best I have been able to do so far is use point breaks at every step to see how far it gets. I've gotten to the controller route so I know that its grabbing the data just fine, my understanding is that it now has the data, and should use the view model to match and display the data. I have gone through about 100 data samples in the view model and it seems fine but there is 2400 units, all with 5 arrays inside of them. However it will simply error out with no message. Any ideas of whats going on or how to debug this? Is there a way in VS Code so see a better log of something like this or another tool that will do that will help in this situation?
** Service Code: **
public async Task<IEnumerable<SapDispatchViewModel>> GetDispatchDeliveryForSap()
{
var result = await _dispatchRepo.GetDispatchDeliveryForSap(TenantId);
var view = new List<SapDispatchViewModel>();
foreach (SapDispatch row in result)
{
var sapView = _mapper.Map<SapDispatch, SapDispatchViewModel>(row);
var items = await _dispatchItemRepo.GetDispatchItemsByTruckForSap(row.DispatchTruckId);
var viewItems = _mapper.Map<IEnumerable<SapDispatchItem>, IEnumerable<SapDispatchItemViewModel>>(items);
sapView.Items = viewItems;
view.Add(sapView);
}
return view;
}
** It calls this GetDispatchDeliveryForSap first: **
public async Task<IEnumerable<SapDispatch>> GetDispatchDeliveryForSap(string TenantId)
{
string deliveryType = "Delivery";
//resort to raw SQL to assist with performance improvements
FormattableString sql = $#"
WITH cte_latestStatus AS
( SELECT * FROM (
SELECT
s.TenantId,
s.DispatchId,
s.DispatchHeaderId,
s.RequestedArrival,
s.EstimatedArrival,
s.Status,
u.FirstName + ' ' + u.LastName UserName,
s.CreateDate StatusChangeDate,
row_number() over(partition by DispatchHeaderId order by CreateDate desc) as rn
FROM
DispatchStatus s
JOIN AspNetUsers u on s.CreateUserId = u.Id
) t
WHERE t.rn = 1
)
select w.wellid,
w.wellname,
wo.ErpId,
wc.ContractorName + ' ' + w.RigNumber Rig,
w.CountyParish County,
w.State,
d.type DispatchType,
u.LastName + ',' + u.FirstName OrderedBy,
ds.RequestedArrival RequestedDate,
dt.DriverName,
dt.SwamperName,
dt.TicketNumber,
dt.DispatchTruckId
from well w
join Dispatch d on w.wellid = d.DestinationWellId
join cte_latestStatus ds on d.DispatchId = ds.DispatchId and d.HeaderId = ds.DispatchHeaderId
join DispatchTruck dt on d.DispatchId = dt.DispatchId
join AspNetUsers u on d.CreateUserId = u.Id
left join WellContractorRef wcr on w.WellId = wcr.WellId
left join Contractor wc on wcr.ContractorId = wc.ContractorId
left join WellOperatorRef wor on w.WellId = wor.WellId
left join Operator wo on wor.OperatorId = wo.OperatorId
--join DispatchItem di on dt.DispatchTruckId = di.DispatchTruckId
where d.TenantId = {TenantId}
and d.type = {deliveryType}
and (ds.Status = 'Completed' or dt.status = 'Completed')
order by w.wellname"
;
var result = await context.SapDispatches.FromSqlInterpolated(sql).AsNoTracking().ToListAsync();
return result;
}
}
}
** Then maps via the view model to create the list: **
namespace Mudman.Model.ViewModels
{
public class SapDispatchViewModel
{
public string WellId { get; set; }
public string WellName { get; set; }
public string ErpId { get; set; }
public string Rig { get; set; }
public string County { get; set; }
public string State { get; set; }
public string DispatchType { get; set; }
public string OrderedBy { get; set; }
public DateTime? RequestedDate { get; set; }
public string DriverName { get; set; }
public string SwamperName { get; set; }
public long? TicketNumber { get; set; }
public IEnumerable<SapDispatchItemViewModel> Items { get; set; }
}
public class SapDispatchItemViewModel
{
public string ErpId { get; set; }
public Decimal? Price { get; set; }
public Decimal? Quantity { get; set; }
public string Size { get; set; }
public string Unit { get; set; }
}
}
** From there, it runs the foreach on the GetDispatchItemsForTruckSap: **
public async Task<IEnumerable<SapDispatchItem>> GetDispatchItemsByTruckForSap(string dispatchTruckId)
{
//resort to raw SQL to assist with performance improvements
FormattableString sql = $#"
WITH cte as (
SELECT
COALESCE(ProductId, ExpenseId) AS SalesItemID,
Price,
Quantity
FROM DispatchItem
WHERE DispatchTruckId = {dispatchTruckId}
)
SELECT si.ErpId,
cte.Price,
cte.Quantity,
si.Size,
si.Unit
FROM SalesItem si
INNER JOIN cte on cte.SalesItemID = si.SalesItemId"
;
var result = await context.SapDispatchItems.FromSqlInterpolated(sql).AsNoTracking().ToListAsync();
return result;
}
}
}
** Maps with the Item View Model: **
public class SapDispatchItemViewModel
{
public string ErpId { get; set; }
public Decimal? Price { get; set; }
public Decimal? Quantity { get; set; }
public string Size { get; set; }
public string Unit { get; set; }
}
}
** Then it will hit the return and thats where it will error out.
Also, here is what the callstack is looking like when you hit that return.
Try turning on Break When Thrown on Common Language Runtime Exceptions and it should break at the error:
How can I query a composite key field in a multiple IN clause SQL?
My Subsidiary is a composite of a String and a Company
public class Company
{
public virtual String Id { get; set; }
}
public class Subsidiary
{
public virtual String Id { get; set; }
public virtual Company Company { get; set; }
}
public class Disponibility
{
public virtual String IdCompany { get; set; }
public virtual String IdSubsidiary { get; set; }
}
Currently stuck at this
var subsidiarys = session.Query<Subsidiary>().ToList();
var result = session.Query<Disponibility>().Where(x => subsidiarys.Contains(???) ).ToList();
The generated query needs to be
SELECT * FROM VW_DISPONIBILITY D
WHERE (D.COMPANY, D.SUBSIDIARY) IN (SELECT S.COMPANY, S.SUBSIDIARY FROM SUBSIDIARY S);
Not all databases support oracle multiple IN clause so the only way to do this is by concatenating multiples or.
var disjunctions = Restrictions.Disjunction();
foreach (var sub in subsidiarys)
{
disjunctions.Add(Restrictions.Where<Disponibility>(x => x.IdCompany == sub.Company.Id && x.IdSubsidiary == sub.Id));
}
var result = session.QueryOver<Disponibility>()
.Where(disjunctions)
.List<Disponibility>();
Generated SQL
SELECT
...
FROM
VW_DISPONIBILITY this_
WHERE
(
(
this_.COMPANY = :p0
and this_.SUBSIDIARY = :p1
)
or (
this_.COMPANY = :p2
and this_.SUBSIDIARY = :p3
)
...
);
I have got two tables,
Feedback Table and Steps Table. Each feedback has multiple Steps. If i use LINQ with join method it returnd same number of step items (obj) in FeedbackViewModel and each contains only 1 single step. I mean ery similar to SQL return.
FeedbackViewModel[0]{FeedbackID = 1,FeedbackName="NameA", Steps{Step1}}
FeedbackViewModel[1]{FeedbackID = 1,FeedbackName="NameA", Steps{Step2}}
FeedbackViewModel[2]{FeedbackID = 1,FeedbackName="NameA", Steps{Step3}}
BUT I only want one FeedbackViewModel object which contains many Steps.
FeedbackViewModel[0]{FeedbackID = 1,FeedbackName="NameA", Steps{Step1, Step2, Step 3 etc..}
I can do it by foreach Loop but it doesn't look professional.
Thanks for help
public class Feedback
{
public int FeedbackID { get; set; }
public string FeedbackName { get; set; }
}
public class StepModel
{
public int StepID { get; set; }
public int FeedbackID { get; set; } = 0;
public int StepNumber { get; set; }
public string StepDetail { get; set; }
public virtual Feedback FeedBack { get; set; }
}
public class FeedbackViewMODEL
{
public int FeedbackID { get; set; }
public string FeedbackName { get; set; }
public List<StepModel> Steps { get; set; }
}
var quote = from feed in FeedBacks
join stp in StePs on feed.FeedbackID equals stp.FeedbackID
where feed.FeedbackID == id
select new FeedbackViewMODEL
{
Step = stp;
}
Using the LINQ group join will combine all the matching steps:
var quote = from feed in FeedBacks
where feed.FeedbackID == id
join stp in StePs on feed.FeedbackID equals stp.FeedbackID into stpj
select new FeedbackViewMODEL {
FeedbackID = feed.FeedbackID,
FeedbackName = feed.FeedbackName,
Steps = stpj.ToList()
};
I think you should left outer join.
from feed in Feedbacks
join stp in steps on feed.FeedbackID equal stp.FeedbackID into result
where feed.FeedBackID == id and result.DefaultIfEmpty()
I have a query in SQL query as like below:
with pagedetail as
(
select
c.componentrefid, l.name, c.startdate,
ROW_NUMBER() over(PARTITION By c.componentrefid order by c.startdate desc) as rownumber
from
FM_componentTransaction as c
inner join
FM_LK_statusinfo as l on c.Statusinforefid = l.refid
inner join
fm_scriptinfo as s on s.Refid = c.ScriptRefId
where
s.CustomerInfoRefId = '85629125-7072-4EFE-9201-97E088E126C6'
)
select
pd.*
from
pagedetail pd
where
pd.rownumber = 1
I can get the output of this. Now my questions is how to implement this query using Entity Framework?
I know this is not a direct answer to your question, however one approach would be to create a stored procedure in SQL, and then just call the stored procedure in Entity Framework.
Code first:
How to call Stored Procedure in Entity Framework 6 (Code-First)?
Database First:
https://msdn.microsoft.com/en-us/data/gg699321.aspx
Assuming you have the following model:
public class ComponentTransaction
{
public Guid componentrefid { get; set; }
public string name { get; set; }
public DateTime startdate { get; set; }
public Guid Statusinforefid { get; set; }
public Guid ScriptRefId { get; set; }
}
public class Statusinfo
{
public Guid refid { get; set; }
}
public class Scriptinfo
{
public Guid refid { get; set; }
public Guid CustomerInfoRefId { get; set; }
}
The code can look like this:
Db db = new Db();
Guid customerInfoRefId = new Guid("85629125-7072-4EFE-9201-97E088E126C6");
var res = db.ComponentTransactions
.GroupBy(c => c.componentrefid)
.Select(g => g.OrderByDescending(c => c.startdate).First())
.Join(db.Statusinfos, c => c.Statusinforefid, l => l.refid, (c, l) => c)
.Join(db.Scriptinfos.Where(s => s.CustomerInfoRefId == customerInfoRefId),
c => c.ScriptRefId, s => s.refid, (c, s) => c);