How to create criteria query for given sql query - c#

I am creating an ICriteria query for this equivalent sql query.
SELECT fCustomerID,
ISNULL(
(SELECT SUM(payinv.fAmount) AS Expr1
FROM dbo.tARPayment AS pay
INNER JOIN dbo.tARPaymentInvoice AS payinv ON pay.fPaymentID = payinv.fPaymentID
INNER JOIN dbo.tARInvoice AS inv ON payinv.fInvoiceID = inv.fARInvoiceID
WHERE (pay.fIsPosted = CASE pay.fPaymentType WHEN 'CM' THEN 0 WHEN 'EPD' THEN 0 ELSE 1 END)
AND (inv.fCustomerID <> dbo.tARCustomer.fCustomerID)
AND (pay.fCustomerID = dbo.tARCustomer.fCustomerID)), 0)
FROM dbo.tARCustomer
GROUP BY fCustomerID
But I am not getting anyway that how can I generate equivalent nhibernate ICriteria query.
This is payment class
public partial class tARPayment
{
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="tARPayment"/> class.
/// </summary>
public tARPayment()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="tARPayment"/> class.
/// </summary>
/// <param name="fPaymentID">The fPaymentID of guid type.</param>
public tARPayment(System.Guid fPaymentID)
{
this.ID = fPaymentID;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets payment id.
/// </summary>
public virtual System.Guid fPaymentID { get; set; }
/// <summary>
/// Gets or sets fCustomerID.
/// </summary>
public virtual System.Guid fCustomerID { get; set; }
/// <summary>
/// Gets or sets check number.
/// </summary>
public virtual string fCheckNumber { get; set; }
/// <summary>
/// Gets or sets amount.
/// </summary>
public virtual decimal fAmount { get; set; }
/// <summary>
/// Gets or sets customer detail.
/// </summary>
public virtual tARCustomer Customer { get; set; }
public virtual IList<tARPaymentInvoice> PaymentInvoices { get; set; }
#endregion
#region Methods
/// <summary>
/// partial class for payment.
/// </summary>
/// <returns>The method get code.</returns>
public override int GetHashCode()
{
return ID.GetHashCode();
}
#endregion
}
This is a invoice class
public partial class tARInvoice
{
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="tARInvoice"/> class.
/// </summary>
public tARInvoice()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="tARInvoice"/> class.
/// </summary>
/// <param name="fARInvoiceID">The fARInvoiceID.</param>
public tARInvoice(System.Guid fARInvoiceID)
{
this.ID = fARInvoiceID;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets fARInvoiceID.
/// </summary>
public virtual Guid fARInvoiceID { get; set; }
/// <summary>
/// Gets or sets fCustomerID.
/// </summary>
public virtual Guid fCustomerID { get; set; }
/// <summary>
/// Gets or sets Delivery Method.
/// </summary>
public virtual string fDeliveryMethod { get; set; }
/// <summary>
/// Gets or sets Invoice Number.
/// </summary>
public virtual int? fARInvoiceNumber { get; set; }
public virtual tARCustomer Customer { get; set; }
public virtual IList<tARPaymentInvoice> PaymentInvoices { get; set; }
#endregion
#region Methods
/// <summary>
/// retrieve Hash Code.
/// </summary>
/// <returns>The method get code.</returns>
public override int GetHashCode()
{
return ID.GetHashCode();
}
#endregion
}
This is a payment invoice class.
public partial class tARPaymentInvoice
{
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="tARPaymentInvoice"/> class.
/// </summary>
public tARPaymentInvoice()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="tARPaymentInvoice"/> class.
/// </summary>
/// <param name="fPaymentInvoiceID">The Invoice ID.</param>
public tARPaymentInvoice(System.Guid fPaymentInvoiceID)
{
this.ID = fPaymentInvoiceID;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets fPaymentInvoiceID.
/// </summary>
public virtual System.Guid fPaymentInvoiceID { get; set; }
/// <summary>
/// Gets or sets fPaymentID.
/// </summary>
public virtual System.Guid fPaymentID { get; set; }
/// <summary>
/// Gets or sets fInvoiceID.
/// </summary>
public virtual System.Guid fInvoiceID { get; set; }
/// <summary>
/// Gets or sets tARPayment.
/// </summary>
public virtual tARPayment Payment { get; set; }
/// <summary>
/// Gets or sets tARInvoice.
/// </summary>
public virtual tARInvoice Invoice { get; set; }
#endregion
#region Methods
/// <summary>
/// get hash codes.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
return ID.GetHashCode();
}
#endregion
}

Rather than converting the above query to LINQ or HQL, I would recommend making the query into a view, and then using NHibernate to query that view.
SQL
CREATE VIEW vCustomerAmount AS
SELECT fCustomerID,
ISNULL(
(SELECT SUM(payinv.fAmount) AS Expr1
FROM dbo.tARPayment AS pay
INNER JOIN dbo.tARPaymentInvoice AS payinv ON pay.fPaymentID = payinv.fPaymentID
INNER JOIN dbo.tARInvoice AS inv ON payinv.fInvoiceID = inv.fARInvoiceID
WHERE (pay.fIsPosted = CASE pay.fPaymentType WHEN 'CM' THEN 0 WHEN 'EPD' THEN 0 ELSE 1 END)
AND (inv.fCustomerID <> dbo.tARCustomer.fCustomerID)
AND (pay.fCustomerID = dbo.tARCustomer.fCustomerID)), 0) [Amount]
FROM dbo.tARCustomer
GROUP BY fCustomerID
C# DTO
public class CustomerAmount
{
public int fCustomerID { get; set; }
public decimal Amount { get; set; }
}
Query
List<CustomerAmount> customerAmounts = session.Query<CustomerAmount>().ToList();

Not sure about nHibernate, but does this rewritten query help get the same answer and is something you can run with easier?
SELECT T.fCustomerID,
coalesce( SUM( payinv.fAmount ), 0 ) as SumAmt
FROM
dbo.tARCustomer T
JOIN dbo.tARPayment AS pay
ON T.fCustomerID = pay.fCustomerID
AND pay.fIsPosted = CASE pay.fPaymentType
WHEN 'CM' THEN 0
WHEN 'EPD' THEN 0
ELSE 1 END
JOIN dbo.tARPaymentInvoice AS payinv
ON pay.fPaymentID = payinv.fPaymentID
INNER JOIN dbo.tARInvoice AS inv
ON payinv.fInvoiceID = inv.fARInvoiceID
AND inv.fCustomerID <> T.fCustomerID
GROUP BY
T.fCustomerID

Related

Column sortorder when writing CSV file using CsvHelper

When writing TSVs from .Net objects file using CsvHelper, I would like to control column sort order using attributes.
When using the CsvHelper-provided Index(..) attribute, I am able to control serialization order, but the column header is suffixed with an index:
Model(s), inherited:
/// <summary>
/// Generic daily data
/// </summary>
public class DailyData
{
/// <summary>
///
/// </summary>
[CsvHelper.Configuration.Attributes.Index(-2, -2)]
public int IdDay {get;set;}
}
/// <summary>
/// Generic hou-on-a-day data
/// </summary>
public class HourlyData : DailyData
{
/// <summary>
///
/// </summary>
[CsvHelper.Configuration.Attributes.Index(-1)]
public byte IdHour { get; set; }
}
/// <summary>
///
/// </summary>
public class HourlyWeatherInfo : HourlyData
{
/// <summary>
///
/// </summary>
public double Temperature { get; internal set; }
}
Output:
IdDay1 IdHour1 Temperature
20220516 18 291.7
20220516 21 289.55
20220517 0 287.3
20220517 3 286.33
I am using negative numbers for indices because I want the base class to have their properties listed first without having to bother with serialization order in the derived classes (like HourlyWeatherInfo.
Am I overlooking functionality?
It feels a bit hacky, but this seems to work.
/// <summary>
/// Generic daily data
/// </summary>
public class DailyData
{
/// <summary>
///
/// </summary>
[CsvHelper.Configuration.Attributes.Index(-2,-3)]
public int IdDay {get;set;}
}
/// <summary>
/// Generic hou-on-a-day data
/// </summary>
public class HourlyData : DailyData
{
/// <summary>
///
/// </summary>
[CsvHelper.Configuration.Attributes.Index(-1,-2)]
public byte IdHour { get; set; }
}
/// <summary>
///
/// </summary>
public class HourlyWeatherInfo : HourlyData
{
/// <summary>
///
/// </summary>
public double Temperature { get; internal set; }
}

Cutting down LINQ Query time

Good morning. I'm trying to cut down the time on a LINQ Query. During the execution of the block of code, against large datasets it takes about 30-40 seconds to complete, which is way too long.
foreach (var patientVisitId in patientVisitIds)
{
var firstVisit = visitsWithBills.First(vb => vb.Visit.PatientVisitId == patientVisitId).Visit;
firstVisit.Bills = (from visitBill in visitsWithBills
where visitBill.Visit.PatientVisitId == patientVisitId
select visitBill.Bill).ToList();
visitTOs.Add(firstVisit);
}
I've tried replacing the == within the where statement with .contains which I read is supposed to be quicker, that almost doubles the execution time.
foreach (var patientVisitId in patientVisitIds)
{
var firstVisit = visitsWithBills.First(vb => vb.Visit.PatientVisitId == patientVisitId).Visit;
firstVisit.Bills = (from visitBill in visitsWithBills
where visitBill.Visit.PatientVisitId.Contains(patientVisitId)
select visitBill.Bill).ToList();
visitTOs.Add(firstVisit);
}
Here's the Object that firstVisit represents.
public class VisitTO
{
#region { Instance properties }
/// <summary>
/// Gets or sets the bed/room number for the visit
/// </summary>
public string Bed { get; set; }
/// <summary>
/// Gets or sets the bills for the visit
/// </summary>
public List<BillTO> Bills { get; set; }
/// <summary>
/// Gets or sets the date of admission for the visit
/// </summary>
public DateTime DateOfAdmission { get; set; }
/// <summary>
/// Gets or sets the primary diagnosis for the patient
/// </summary>
public string DX1 { get; set; }
/// <summary>
/// Gets or sets the secondary diagnosis for the patient
/// </summary>
public string DX2 { get; set; }
/// <summary>
/// Gets or sets the tertiary diagnosis for the patient
/// </summary>
public string DX3 { get; set; }
/// <summary>
/// Gets or sets the quaternary diagnosis for the patient
/// </summary>
public string DX4 { get; set; }
/// <summary>
/// Gets or sets the quinary diagnosis for the patient
/// </summary>
public string DX5 { get; set; }
/// <summary>
/// Gets or sets the senary diagnosis for the patient
/// </summary>
public string DX6 { get; set; }
/// <summary>
/// Gets or sets whether the patient has been discharged
/// </summary>
public bool IsDischarged { get; set; }
/// <summary>
/// Gets or sets the patient's full name
/// </summary>
public string PatientName { get; set; }
/// <summary>
/// Gets or sets the patient's current visit ID
/// </summary>
public string PatientVisitId { get; set; }
/// <summary>
/// Gets or sets the patient's current visit ID
/// </summary>
public string PatientId { get; set; }
/// <summary>
/// Gets or sets the name of the patient's primary care physician
/// </summary>
public string PrimaryCarePhysician { get; set; }
/// <summary>
/// Gets or sets the hosting site
/// </summary>
public string Site { get; set; }
/// <summary>
/// Gets or sets the team assignment
/// </summary>
public string Team { get; set; }
#endregion { Instance properties }
}
Here's BillTO object.
public class BillTO
{
#region { Public instance properties }
/// <summary>
/// Gets or sets the bill's date
/// </summary>
public DateTime Date { get; set; }
/// <summary>
/// Gets or sets the name for the doctor on the bill
/// </summary>
public string DoctorName { get; set; }
/// <summary>
/// Gets or sets the bill's type
/// </summary>
public string Type { get; set; }
/// <summary>
/// Gets or sets the encounter for this bill
/// </summary>
public string Encounter { get; set; }
/// <summary>
/// Gets or sets the CPT Code
/// </summary>
public string CptCode { get; set; }
#endregion { Public instance properties }
}
Database Query to the get the list.
private static readonly Func<MDataContext, IQueryable<VisitBillTO>> ActiveVisitsWithBillsQuery =
CompiledQuery.Compile<MContext, IQueryable<VisitBillTO>>(
dbContext => (
from visit in dbContext.AV
join bill in dbContext.ABills on visit.PatientVisitId equals bill.PatientVisitId
where (visit.BFlag == null || visit.BFlag != "BI")
orderby visit.PatientVisitId
select new VisitBillTO
{
Bill = new BillTO
{
Date = bill.Date.GetValueOrDefault(DateTime.Today),
DoctorName = bill.DoctorName,
Type = bill.Type,
Encounter = bill.Encounter,
CptCode = bill.CptCode
},
Visit = new VisitTO
{
Bed = visit.Bed,
DateOfAdmission = visit.DateOfAdmission.GetValueOrDefault(DateTime.Today),
DX1 = visit.DX1,
DX2 = visit.DX2,
DX3 = visit.DX3,
DX4 = visit.DX4,
DX5 = visit.DX5,
DX6 = visit.DX6,
IsDischarged = (visit.IsDischargedCode != null && visit.IsDischargedCode == "Y"),
PatientName = (visit.PatientFullName ?? visit.PatientLastName + ", " + visit.PatientFirstName),
PatientVisitId = visit.PatientVisitId,
PatientId = visit.PatientID,
PrimaryCarePhysician = visit.PrimaryCarePhysician,
Site = visit.Site,
Team = visit.Team
}
}
));
As I expected, you can do this far more efficiently in one query:
from visit in dbContext.AV
where (visit.BFlag == null || visit.BFlag != "BI")
&& patientVisitIds.Contains(visit.PatientVisitId)
orderby visit.PatientVisitId
select new VisitBillTO
{
Bed = visit.Bed,
...
Team = visit.Team,
Bills = (from bill
in visit.Bills
select new BillTO
{
Date = bill.Date.GetValueOrDefault(DateTime.Today),
DoctorName = bill.DoctorName,
Type = bill.Type,
Encounter = bill.Encounter,
CptCode = bill.CptCode
})
}
Now the database does all the heavy lifting of combining the objects. Everything is shaped as you want in one go.
Note that I assume the navigation property visit.Bills to exist. These properties normally exist in LINQ-to-SQL contexts, but in the designer for some reason they're always collapsed by default, so people tend to overlook them. If for some reason the property isn't there you can replace...
Bills = (from bill in visit.Bills
by...
Bills = (dbContext.ABills where visit.PatientVisitId == bill.PatientVisitId

Web API Help page doesn't show documentation of extended object

Tldr;
I have a object that extends from another object.
/// <summary>
/// Represents the result of an operation
/// </summary>
[DataContract]
public class ApiResult<T> : ApiResult
{
/// <summary>
/// The requested data
/// </summary>
[DataMember]
public T Data { get; private set; }
/// <summary>
/// Test
/// </summary>
[DataMember]
public string Test { get; private set; }
Every property of ApiResult is documented, but not the properties of ApiResult<T>:
Why is the documentation description blank for a extended object? I expected that my <summary> is used here. How can I make it show?
More Details
Here is the full code:
/// <summary>
/// Represents the result of an operation
/// </summary>
//[DataContract(Name = "ApiResult")]
public class ApiResult
{
/// <summary>
/// Indicates if the operation was performed successfull. If an error occured more Information are available in ErrorCode and Message.
/// </summary>
[DataMember]
public bool IsSuccess { get; private set; }
/// <summary>
/// A programmable static reason, if the operation was not successfull. This can be ignored on successfull state.
/// </summary>
[DataMember]
public int ErrorCode { get; private set; }
/// <summary>
/// Additional information about the error, if the operation was not successfull. This is only for Information purpose. Use the ErrorCode for business conditions instead.
/// </summary>
[DataMember]
public string Message { get; private set; }
/// <summary>
/// Creates a Success Result
/// </summary>
public ApiResult()
{
IsSuccess = true;
ErrorCode = 0;
Message = "ok";
}
/// <summary>
/// Creates a Error Result
/// </summary>
/// <param name="errorCode">The error code</param>
/// <param name="message">The message</param>
public ApiResult(int errorCode, string message)
{
IsSuccess = false;
ErrorCode = errorCode;
Message = message;
}
}
/// <summary>
/// Represents the result of an operation
/// </summary>
//[DataContract(Name = "ApiResult")]
public class ApiResult<T> : ApiResult
{
/// <summary>
/// The requested data
/// </summary>
[DataMember]
public T Data { get; private set; }
/// <summary>
/// Test
/// </summary>
[DataMember]
public string Test { get; private set; }
/// <summary>
/// Creates a Success Result without having an actualy Result
/// <remarks>This constructor should not be used. A parameterless constructor is needed for the automatic generation of a Documentation Example.</remarks>
/// </summary>
//[EditorBrowsable(EditorBrowsableState.Never)]
//[Obsolete("Use the nongeneric version of ApiResult instead. This CTOR is only to support XmlSerialization.")]
public ApiResult()
{
}
/// <summary>
/// Creates a Success Result
/// </summary>
/// <param name="data">The data</param>
public ApiResult(T data)
{
Data = data;
}
/// <summary>
/// Creates a Error Result
/// </summary>
/// <param name="errorCode">The error code</param>
/// <param name="message">The message</param>
public ApiResult(int errorCode, string message) : base(errorCode, message)
{
}
}
And here my Method signature:
public ApiResult<CardInfo> GetCardInfo(string cardNumber)
Just in case, here is my CardInfo-class:
/// <summary>
/// Information about a card
/// </summary>
public class CardInfo
{
/// <summary>
/// Card Type
/// </summary>
public string CardType { get; set; }
/// <summary>
/// Represents the current credit on card.
/// Prepaid cards: CurrentValue represents the current credit on card.
/// Postpaid: CurrentValue represents the monthly available credit amount.
/// </summary>
public decimal CurrentValue { get; set; }
}
My Question is about the automatic generated Help Page in Web API 2. The <summary> is ignored on the helppage, if the Class is extended.

Display name does not exist in the current context

The name '' does not exist in the current context
crn
courseid
timedays
Roomnumber
At the display, none of the items are recognized. Why is the display not seeing them when they were declared as set and gets?
using System;
using System.Collections.Generic;
using System.Text;
public class Section
{
private int crn;
private String courseId;
private String timeDays;
private String roomNumber;
private int instructor;
/// <summary>
/// Creates a new instance of a section
/// </summary>
/// <param name="crn"></param>
/// <param name="courseId"></param>
/// <param name="timeDays"></param>
/// <param name="roomNumber"></param>
/// <param name="instructor"></param>
public Section(int crn, string courseId, string timeDays, string roomNumber, int instructor)
:this(crn, courseId, timeDays, roomNumber, instructor, "")
{
}
/// <summary>
/// Creates a new instance of a section
/// </summary>
/// <param name="crn"></param>
/// <param name="courseId"></param>
/// <param name="timeDays"></param>
/// <param name="roomNumber"></param>
/// <param name="instructor"></param>
/// <param name="message"></param>
public Section(int crn, string courseId, string timeDays, string roomNumber, int instructor, string message)
{
this.Crn = crn;
this.CourseId = courseId;
this.TimeDays = timeDays;
this.RoomNumber = roomNumber;
this.Instructor = instructor;
this.Message = message;
}
/// <summary>
/// Gets or sets the crn
/// </summary>
public int Crn { get; set; }
/// <summary>
/// gets or sets the course id
/// </summary>
public string CourseId { get; set; }
/// <summary>
/// gets or sets the time days
/// </summary>
public string TimeDays { get; set; }
/// <summary>
/// gets or sets the room number
/// </summary>
public string RoomNumber { get; set; }
/// <summary>
/// Gets or sets the instructor
/// </summary>
public int Instructor { get; set; }
/// <summary>
/// Gets or sets the message
/// </summary>
public string Message { get; set; }
public void display(){
System.Console.WriteLine("CRN = "+ getCrn());
System.Console.WriteLine("CourseID = "+ getCourseId());
System.Console.WriteLine("Time Days = " + getTimeDays());
System.Console.WriteLine("Room Number = " + getRoomNumber());
}
}
I think display() needs to look like below. I don't know how your display() function is even compiling.
public void display()
{
System.Console.WriteLine("CRN = "+ Crn);
System.Console.WriteLine("CourseID = "+ CourseId);
System.Console.WriteLine("Time Days = " + TimeDays);
System.Console.WriteLine("Room Number = " + RoomNmber);
}
In addition, since you have all your properties declared with { get; set; }, you don't need any backing member variables (the compiler automatically takes care of these for you). So you can delete the lines that look like this:
private int crn;
private String courseId;
private String timeDays;
private String roomNumber;
private int instructor;

Simple JsonConvert.DeserializeObject not assigning properties

This should work and it's very basic. My json string is (from the debugger):
json "{\"companyId\":0,\"companyName\":\"Windward 3\",\"apiKey\":null,\"isEnabled\":false,\"isActive\":false,\"accruedRtusThisMonth\":0,\"billedRtusThisMonth\":0,\"overageChargesThisMonth\":0.0,\"pricingMode\":3,\"discount\":null,\"billingMode\":1,\"maxAdditionalMonthlyCharge\":123.0,\"billing\":{\"personId\":0,\"companyId\":0,\"isActive\":false,\"isAdmin\":false,\"isBilling\":false,\"firstName\":\"David\",\"lastName\":\"Thielen\",\"address1\":\"1 Main St.\",\"address2\":null,\"city\":\"Boulder\",\"state\":\"CO\",\"country\":\"USA\",\"postalCode\":\"80301\",\"phone\":\"123-456-7890\",\"email\":\"david#windward.net\",\"password\":\"tree\"},\"creditCard\":{\"cardNumber\":\"4111111111111111\",\"expiration\":\"2015-02-18T23:37:01.3135786Z\",\"cvv\":\"123\",\"useCardPerson\":false,\"cardPerson\":null},\"nextBaseBillingDate\":\"0001-01-01T00:00:00\",\"nextOverageBillingDate\":\"0001-01-01T00:00:00\",\"billingStatus\":0,\"billingErrorDate\":null,\"deactivateDate\":null,\"deleteDate\":null}" string
My code is as follows:
CompanyWrapper companyWrapper = JsonConvert.DeserializeObject<CompanyWrapper>(json,
new JsonSerializerSettings());
And the CompanyWrapper class is:
public class CompanyWrapper
{
/// <summary>
/// For the JSON population.
/// </summary>
public CompanyWrapper()
{
}
/// <summary>
/// For unit tests
/// </summary>
public CompanyWrapper(string companyName, PricingPlan.PRICING_MODE pricingMode, Company.BILLING_MODE billingMode, decimal maxAdditionalMonthlyCharge, PersonWrapper billing, CreditCardWrapper creditCard)
{
this.companyName = companyName;
this.pricingMode = pricingMode;
this.billingMode = billingMode;
this.maxAdditionalMonthlyCharge = maxAdditionalMonthlyCharge;
this.billing = billing;
this.creditCard = creditCard;
}
/// <summary>
/// The primary key. This is auto-generated in the database.
/// </summary>
public int companyId { get; private set; }
/// <summary>
/// The company name. This cannot be changed.
/// </summary>
public string companyName { get; private set; }
...
}
On return companyWrapper.companyName == null. That should be assigned. What am I missing?
thanks - dave
You need to make the property setters public.

Categories

Resources