I am trying to figure out how to best query in NHibernate so that the returned results are between for entries where todays time is >= PublishDateTime and <=ExpiryDateTime
The expiry date can be null so I need to allow for that. I found a couple of examples here and here but they seem to work in a different way and accept 2 values and compare to one DB field. I want the other way wrong really.
Query so far:
var query = _session.CreateCriteria<Message>()
.AddOrder(Order.Desc("PublishedDateTime"))
.List<Message>();
return query;
Any suggestions would be greatly received!
Easiest Linq query:
return _session.Query<Message>()
.Where(m => DateTime.Today >= m.PublishDateTime &&
(m.ExpiryDateTime == null ||
DateTime.Now <= m.ExpiryDateTime)
.OrderByDescending(m => m.PublishDateTime)
.ToList();
Criteria:
return _session.CreateCriteria<Message>()
.Add(Restrictions.Le("PublishedDateTime", DateTime.Today) &
(Restrictions.IsNull("ExpiryDateTime") |
Restrictions.Ge("ExpiryDateTime",
DateTime.Now)))
.AddOrder(Order.Desc("PublishedDateTime"))
.List<Message>();
In c# :
var formato = "dd/MM/yyyy h:mm:ss";
var sDesde = DateTime.Now.ToString("dd/MM/yyyy") + " 0:00:00";
var sHasta = DateTime.Now.ToString("dd/MM/yyyy h:mm:ss");
Viaje vDesde = new Viaje { Viajefecha = DateTime.ParseExact(sDesde, formato , null) };
Viaje vHasta = new Viaje { Viajefecha = DateTime.ParseExact(sHasta, formato, null) };
StringWriter strWriter = new StringWriter();
var resultado = cp.sesion.CreateCriteria<Viaje>().Add(Expression.Between("Viajefecha", vDesde.Viajefecha, vHasta.Viajefecha)).AddOrder(Order.Asc("Viajefecha")).List<Viaje>();
Related
I want to count the number of records contained in the Suspenses property with a year of "2013" and a month of "1".
I get the error when I run the below code: "DbComparisonExpression requires arguments with comparable types." I'm still new to ASP.Net MVC, not sure if this is the way to get my results. Hopefully I can learn from your comments. Your help will be appreciated.
var suspenses = db.Suspenses.Include(s => s.User);
int[] count = new int[12];
for (var i = 1; i <= 12; i++)
{
// to count number of account suspenses on every months
suspenses = suspenses.Where(s => s.SuspenseDate.Year.Equals(year));
suspenses = suspenses.Where(s => s.SuspenseDate.Month.Equals(i));
count[i-1] = suspenses.Count();
}
Try this:
int recordsInJanuary2013 =
db.Suspenses.Count(se => se.SuspenseDate.Month == 1
&& se.SuspenseDate.Year == 2013);
You can do it in a single line by grouping per month and counting the total like this :
var count = db.Suspenses.GroupBy(s => s.SuspenseDate.Month).Select(g=>g.Count());
you can use sum in your order
var suspenses = db.Suspenses.sum(s => s.User).where(m => m.mounth == 12);
I have this code written so far and it works for what I am doing but if I search for June 13 it will only look up until June 12, can someone help me figure whats wrong in my code? or where I can add a day interval? I tried and its just not working for me.
var db = Database.Open("RMS") ;
var selectCommand = "SELECT * FROM RMS";
var formSSO = "";
var fromDate= "";
var toDate= "";
formSSO = Request.QueryString["formSSO"];
fromDate = Request.QueryString["fromDate"];
toDate = Request.QueryString["toDate"];
selectCommand = "(SELECT * from RMS WHERE SSO LIKE #0)";
if(!Request.QueryString["fromDate"].IsEmpty() ) {
selectCommand = "SELECT * FROM RMS WHERE SSO LIKE #0 AND Created BETWEEN #1 AND #2";
}
if(Request.QueryString["formSSO"].IsEmpty() ) {
<div class="simple"><strong>*SSO ID is Required.</strong></div>
}
var data = db.Query(selectCommand, formSSO, fromDate, toDate);
var columns = new[]{"ID", "SSO", "Category", "System", "Subject", "Created"};
var grid = new WebGrid(data, ajaxUpdateContainerId: "grid", defaultSort: "ID", columnNames: columns);
if (Request.QueryString[grid.SortDirectionFieldName].IsEmpty()) {
grid.SortDirection = SortDirection.Descending;
}
}
One thing you can try is using <= and >= instead of BETWEEN like this:
selectCommand = "SELECT * FROM RMS WHERE SSO LIKE #0 AND Created >= #1 AND Created <= #2";
I hope that does the trick!
If not you can also brute force the to date to be one day further into the future and then use the BETWEEN operator just you are now like this:
DateTime to_date = Convert.ToDateTime(to_date_string);
to_date = to_date.AddDays(1);
to_date_string = to_date.ToString();
I got the error: ORA-00933: SQL command not properly ended when run the follow linq query at LinqPad V4.42.14(AnyCPU), database is Oracle 11g.
If I replace
where coof.CoofCode == tod.PatTrnsplntFail.CoofCode && coof.OrgCode == prod.OrgCode
to
where coof.CoofCode == tod.PatTrnsplntFail.CoofCode
it works, but I can not remove that factor.
Any body can help me out will be great appreciate.
void Main()
{
var q = (from pat in Pats
from patr in pat.PatRegisters
from prod in patr.PatRegisterOrgDets
from tod in prod.TransplantOrgDets
select new {
PatId = pat.PatID,
FullName = pat.FirstName + ", " + pat.LastName,
RegisterDate = patr.RegDate.ToString("yyyy-MMM-dd"),
TransplantDate = tod.Transplant.TransplantDate.ToString("yyyy-MMM-dd"),
OrganSpec = tod.OrgSpec.Descrip,
IsTransplantedFailed = tod.PatTrnsplntFail.TodID == 0 ? false: true,
TransplantedFailReason = from coof in CausesOfOrgFail
where coof.CoofCode == tod.PatTrnsplntFail.CoofCode && coof.OrgCode == prod.OrgCode
select coof.Descrip
}).Distinct().OrderBy(o => o.PatId);
q.Dump(true);
}
I found a work around way to avoid the issue, but acturally I do not think this is a good way, I fell the LinqPad Oracle Driver has internal bugs cause that issue. Joeseph if you could read this, please give your suggestion. So use the follow linq query instead:
void Main()
{
var q1 = (from pat in Pats
from patr in pat.PatRegisters
from prod in patr.PatRegisterOrgDets
from tod in prod.TransplantOrgDets
where tod.PatTrnsplntFail.TodID == null
select new {
PatId = pat.PatID,
FullName = pat.FirstName + ", " + pat.LastName,
RegisterDate = patr.RegDate.ToString("yyyy-MMM-dd"),
TransplantDate = tod.Transplant.TransplantDate.ToString("yyyy-MMM-dd"),
OrganSpec = tod.OrgSpec.Descrip,
IsTransplantedFailed = false,
CausesOfOrgFailReason = ""
}).Distinct().OrderBy(o => o.PatId);
var q2 = (from pat in Pats
from patr in pat.PatRegisters
from prod in patr.PatRegisterOrgDets
from tod in prod.TransplantOrgDets
from coof in CausesOfOrgFail where coof.CoofCode == tod.PatTrnsplntFail.CoofCode && coof.OrgCode == prod.OrgCode
where tod.PatTrnsplntFail.TodID != null
select new {
PatId = pat.PatID,
FullName = pat.FirstName + ", " + pat.LastName,
RegisterDate = patr.RegDate.ToString("yyyy-MMM-dd"),
TransplantDate = tod.Transplant.TransplantDate.ToString("yyyy-MMM-dd"),
OrganSpec = tod.OrgSpec.Descrip,
IsTransplantedFailed = true,
CausesOfOrgFailReason = coof.Descrip
}).Distinct().OrderBy(o => o.PatId);
q1.ToList().Union(q2.ToList()).OrderBy(o => o.PatId).Dump(true);
}
I have a Personnel Roles Table where employees are assigned daily roles or roles with specific start and end dates.
Managers have asked for a sort of manpower plan table which lists an employee’s daily role and this how I generate the table
private string CreateHTMLTable(Int32 month)
{
StringBuilder strBuilder = new StringBuilder();
System.Data.DataTable dtAllStaff = new System.Data.DataTable();
//get all staff
PersonelApplication.Classes.PersonelClass PersonnelClass = new PersonelClass();
dtAllStaff = PersonnelClass.GetAllPersonel();
//create manpower data table
System.Data.DataTable dtManPowerDataTable = new System.Data.DataTable();
//create montlhy dt
//get number of days in month
int daysInMonth = DateTime.DaysInMonth(DateTime.Now.Year, month);
//get first day in month
DateTime firstDayInMonth = new DateTime(DateTime.Now.Year, month, 1);
//get last day in month
DateTime lastDayInMonth = new DateTime();
lastDayInMonth = firstDayInMonth.AddMonths(1).AddDays(-1);
//start table
strBuilder.Append("<table>");
//create header based on number of days in the month
//append tr strat
strBuilder.Append("<tr>");
//add name header for personnle
strBuilder.Append("<th>");
strBuilder.Append("Staff");
strBuilder.Append("</th>");
for (int i = 1; i <= lastDayInMonth.Day; i++)
{
strBuilder.Append("<th>");
strBuilder.Append(i.ToString() + "/" + month.ToString());
strBuilder.Append("</th>");
}
//append tr end to header row
strBuilder.Append("</tr>");
System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection();
sqlConn.ConnectionString = ConnectionClass.CreateConnection.getConnectionString();
using (sqlConn = ConnectionClass.CreateConnection.publicGetConn())
{
sqlConn.ConnectionString = ConnectionClass.CreateConnection.getConnectionString();
try
{
sqlConn.Open();
if (sqlConn.State == ConnectionState.Open)
{
foreach (DataRow row in dtAllStaff.Rows)
{
string personnelName = "";
string personnelCode = "";
Int32 personnelID = 0; ;
personnelCode = row[1].ToString();
strBuilder.Append("<tr>");
strBuilder.Append("<td>");
strBuilder.Append(personnelCode);
strBuilder.Append("</td>");
for (int i = 1; i <= lastDayInMonth.Day; i++)
{
//here get the each employee's planned role as well
//as actual role
}
strBuilder.Append("</tr>");
}
}
}
catch (Exception ex)
{
//pouplate later
}
finally
{
}
}
//end table
strBuilder.Append("</table>");
return strBuilder.ToString();
}
My issue is the SQL function which will return the employees role for a particular day.
--actual end date for this role is '08-18-2012'
declare #sdate date
set #sdate= '08-14-2012'
SELECT
CONVERT(date,startdate,101)
,CONVERT(date,EndDate,101)
,StartDate
,EndDate
,fk_PersonelID
,fk_RoleID
FROM [dbo].JobRolesTable
where #sdate between StartDate and EndDate
and fk_PersonelID = 40
But If I do a search for the next day which is the '08-15-2012’,I get nada
Bascially I want to return an employee’s role on any day of the month and ‘na’ if there’s none
I don’t want to use a cursor for this but is there another way I can achieve this
DECLARE #sdate DATE = '20120814';
SELECT
CONVERT(DATE,StartDate,101) -- what is the purpose of 101 here?
,CONVERT(DATE,EndDate,101) -- what is the purpose of 101 here?
,StartDate
,EndDate
,fk_PersonelID
,fk_RoleID
FROM [dbo].JobRolesTable
WHERE #sdate >= StartDate
AND #sdate < DATEADD(DAY, 1, EndDate)
AND fk_PersonelID = 40;
You are probably populating your parameters incorrectly.
If your query is of the form
SELECT *
FROM Table
WHERE (#SearchDate BETWEEN #StartDate AND #EndDate) AND Id=#Id
(which yours appears to be), then it will return the correct values from the db as long as the dates are being specified correctly.
Can you show the code where you're actually attempting to use the SqlConnection that you're opening in the posted code?
Is there a online system which converts SQL - LINQ or can anyone else help convert the SQL - LINQ below?
SELECT MIN(startTime) As startTime, MAX(endTime) As endTime
FROM tblRA
LEFT JOIN tblA ON tblRA.asID = tblA.asID
WHERE 'xxxxxx' BETWEEN tblRA.startDate AND tblRA.endDate
AND tblA.availabilityDayOfWeek = 7
The main area I am having trouble is the .MAX/.MIN.
Heres what I have so far
public List<string> GetResourceAvailabilitiesByDate(DateTime searchDate)
{
DayOfWeek dayOfWeek = searchDate.DayOfWeek;
var minVal = from a in dc.tblResourceAvailabilities
join b in dc.tblAvailabilities on a.asID equals b.asID
where searchDate.Date >= a.startDate.Date && searchDate.Date <= a.endDate.Value.Date
&& b.availabilityDayOfWeek == (int)dayOfWeek
select b.startTime.ToShortTimeString();;
var maxVal = from a in dc.tblResourceAvailabilities
join b in dc.tblAvailabilities on a.asID equals b.asID
where searchDate.Date >= a.startDate.Date && searchDate.Date <= a.endDate.Value.Date
&& b.availabilityDayOfWeek == (int)dayOfWeek
select b.endTime.ToShortTimeString();
var min = minVal.Min(minVal.Min);
var max = maxVal.Max();
return min,max;
Thanks in advance for any help
Clare
I think your code is a little bit incorrect, and the first symptom of it is that you are using repeated code to define minval and maxval. I tried to simulate something similar to what you want and came to the following code, please adapt it to your needs.
public List<string> GetResourceAvailabilitiesByDate(DateTime searchDate)
{
DayOfWeek dayOfWeek = searchDate.DayOfWeek;
var vals = from a in dc.tblResourceAvailabilities
join b in dc.tblAvailabilities on a.asID equals b.asID
where searchDate.Date >= a.startDate.Date && searchDate.Date <= a.endDate.Value.Date
&& b.availabilityDayOfWeek == (int)dayOfWeek
select b;
var min = vals.Min(v => v.startTime).ToShortTimeString();
var max = vals.Max(v => v.startTime).ToShortTimeString();
return new List<string>() { min, max };
}
Some comments on your code, assuming it's C#.
You are trying to return an array of strings when you should be returning an array of dates.
Your where clause is pretty confuse. You're comparing the search date with startdate.Date and endDate.Value.Date. It does not make much sense.
Your select clause could select only b, or a, or whatever. You don't really need to select the date in it.