So i have a query that is getting data correctly but as soon as I try to filter out the linq statement with a where between dates, I consistently get zero results.
var query= Enumerable.Empty<CustomClass>().AsQueryable();
query= (from auto in db.AutoInvs
join deal in db.Deals on new { inv = auto.INVUID, client = auto.CLIENTID, acct = auto.ACCOUNT} equals new {inv = deal.INVUID,client = deal.CLIENTID, acct = (int?) deal.ACCOUNT}
join dmCust in db.DMCusts on new {inv = auto.INVUID, client = auto.CLIENTID, acct = auto.ACCOUNT.ToString()} equals new {inv = dmCust.INVUID, client = dmCust.CLIENTID, acct = dmCust.ACCOUNT}
join act in db.Acts on new { inv = auto.INVUID, client = auto.CLIENTID, acct = auto.ACCOUNT.ToString()} equals new { inv = act.INVUID, client = act.CLIENTID, acct = act.Key }
where auto.DATAPROCESSEDDATE == null && auto.INVUID != ""
select new CustomClass()
{
AutoInv = auto,
Deal = deal,
DmCust = dmCust,
Act = act
});
var filteredData = query.Where(c => c.AutoInv.DATESOLD >= dateFrom.Value && c.AutoInv.DATESOLD <= dateTo.Value).AsQueryable();
Console.WriteLine(filteredData.ToList().Count);
Using this stripped down version (and my own data), it works for me:
var query = Enumerable.Empty<Tbl1>().AsQueryable();
DateTime? dateFrom = new DateTime(2017, 5, 10);
DateTime? dateTo = new DateTime(2017, 5, 20);
query = (from auto in db.Tbl1s
select auto);
var filteredData = query.Where(c => c.StartDate >= dateFrom.Value
&& c.StartDate <= dateTo.Value).AsQueryable();
filteredData.Dump();
One possible problem you may be having is that dateTo would be the exclusive end point --- Unless DATESOLD is exactly midnight, you won't get any that are on the end date.
Related
I am facing issues in using order by with group by in linq queries. when I apply group by after order by the ordering is being lost using the following code.
I want to sort all the conversations where type is in ascending. I doubt using Select(x=>x.FirstOrDefault()) is creating some issue.
I am using LINQ queries like this
DateTime? convStartDate = DateTime.Now.AddDays(-90);
DateTime? convEndDate = DateTime.Now;
var limit = 1000;
var offset = 0;
var query = (from conversation in db.textMessagesconversation
join msgParticipants in db.participants on conversation.Id equals msgParticipants.ConversationId
join msg in db.MsgMessages on conversation.Id equals msg.ConversationId
where msgParticipants.UserId == userID && ( (String.IsNullOrEmpty(convStartDate.ToString()) || msg.DateCreatedTime >= convStartDate)
&& (String.IsNullOrEmpty(convEndDate.ToString()) || msg.DateCreatedTime <= convEndDate)
select new RawConversation
{
LastMessageContent = msg.Content,
LastMessageDateTime = msg.DateCreatedTime,
IsAttachment = msg.IsAttachment,
SenderId = msg.SenderId,
MessageId = msg.Id,
Type = conversation.Type,
Name = conversation.Name,
Id = conversation.Id
});
query = query.OrderBy(x => x.Type);
var textmessagesList= query.GroupBy(x=>x.Id).Select(x=>x.FirstOrDefault()).Skip(offset).Take(limit).ToList();
I have seen there are quite a number of references on this error here on SO but I am not able to relate the solutions to fix mine. In my case I am trying to merge two different tables with similar fields. below is the controller action
public IEnumerable Report(int? year, Guid? gcode)
{
DateTime startdate = (new DateTime(DateTime.Now.Year - 1, 7, 1));
DateTime enddate = (new DateTime(DateTime.Now.Year, 6, 30));
//get all online payments
var c = from of in db.OnlinePayments.Include(i => i.Customer).ToList()
select new { of.Customer, of.CustomerID, of.PDate, of.Pay, of.POK };
// get all offline payments
var b = from pa in db.OfflinePayments.Include(i => i.Customer).ToList()
select new { pa.Customer, pa.CustomerID, pa.PDate, pa.Pay,pa.POK };
var all = c.Concat(b);
var query =
(from bk in db.Customers.Where(a=>a.Active)
join tr in all.Where(x => x.PDate >= startdate && x.PDate <= enddate && x.POK && x.CustomerID!=2)
on bk.CustomerID equals tr.CustomerID into trs
select new CViewModel
{
Name = bk.FirstMiddleLastName,
custguid = bk.CustGuid.GetValueOrDefault(),
TotalPaid = (int?)trs.Sum(e => e.Pay) ?? 0
});
return query.AsEnumerable();
}
Any help will be appreciated.
So i'm using Quartz to create a task scheduler for my program and I'm having issues where if there are multiple jobs to run, it will repeatedly execute the query for the respective job but then never exectues the very next line. It's as if it hangs as soon as i hit tolist(). Any ideas?
try
{
//work on query further , need to get client ID correctly
if (vehicleses.Count == 0)
return null;
string siteId = QueryExportSiteWithId(exportSiteId).SiteId;
string clientId = vehicleses[0].ClientID;
db.Database.Log = Console.Write;
var inventoryyReturn = from i in db.Inventory_Vehicles
where dealerIdList.Any(c => c == i.ClientID) && i.Archived != "1" && i.Holding != "1" &&
i.Status == "A"
select i;
var inventoryDescription = from i in db.Inventory_Descriptions
where
inventoryyReturn.Any(
c => new {client = c.ClientID, inv = c.ID} == new {client = i.ClientID, inv = i.InventoryID})
select i;
var settingsExports = from i in db.Settings_Exports
where inventoryyReturn.Any(c => c.ClientID == i.ClientID)
select i;
var settingLots = from i in db.Settings_Lots
where
inventoryyReturn.Any(
c => new {client = c.ClientID, lot = c.LotID} == new {client = i.ClientID, lot = i.ID})
select i;
var inventoryFeatures = from i in db.Inventory_Features
where
inventoryyReturn.Any(
c => new {client = c.ClientID, inv = c.ID} == new {client = i.ClientID, inv = i.InventoryID})
select i;
var inventoryPhotos = from i in db.Inventory_Photos
where
inventoryyReturn.Any(c => c.ID == i.InventoryID)
select i;
var longReturnListt = (from i in inventoryyReturn
join l in inventoryDescription on new {inv = i.ID, cli = i.ClientID} equals
new {inv = l.InventoryID, cli = l.ClientID} into descGroup
from m in descGroup.DefaultIfEmpty()
join s in settingsExports on i.ClientID equals s.ClientID into settingGroup
from sg in settingGroup.DefaultIfEmpty()
join sl in settingLots on new {client = sg.ClientID, lot = sg.LotID} equals
new {client = sl.ClientID, lot = sl.ID} into lotsGroup
from lg in lotsGroup.DefaultIfEmpty()
join se in db.Settings_ExportSites on new {client = lg.ClientID, lotId = i.LotID, site = siteId}
equals new {client = se.ClientID, lotId = se.LotID, site = se.Site} into exportGroup
from eg in exportGroup.DefaultIfEmpty()
join f in inventoryFeatures on new {inv = i.ID, cli = i.ClientID} equals
new {inv = f.InventoryID, cli = f.ClientID} into invFeatGroup
from ifg in invFeatGroup.DefaultIfEmpty()
join p in inventoryPhotos on i.ID equals p.InventoryID into photo
from photos in photo.DefaultIfEmpty()
orderby i.ID
select new {i, m, sg, photoo = photo.ToList(), lg, ifg, eg}
into grouped
group grouped by new {grouped.i.ClientID}
into groupedDone
//select groupedDone
from categories in groupedDone
select new NewType
{
InventoryVehicles = categories.i,
InventoryDescriptions = categories.m,
SettingsExports = categories.sg,
InventoryPhotos = categories.photoo,
SettingsLots = categories.lg,
InventoryFeatures = categories.ifg,
SettingsExportSites = categories.eg
}
).ToList();
// var sql = ((System.Data.Entity.Core.Objects.ObjectQuery) longReturnListt as ObjectQuery);
// var trace = sql.ToTraceString();
if (longReturnListt != null)
{
//returnList.AddRange(longReturnListt.);
return returnList;
}
return null;
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
I have two lists as follows:
var SeparatedEmployees = (from s in DataContext.HRM_EMP_TRMN.AsEnumerable()
where s.TRMN_FINL_STUS == "SA" && ((Convert.ToDateTime(s.TRMN_EFCT_DATE)).Year).ToString() == Year && ((Convert.ToDateTime(s.TRMN_EFCT_DATE)).Month).ToString() == HRMD_COMMON.ReturnMonthName(Month)
join e in DataContext.VW_HRM_EMPLOYEE on s.EMP_CODE equals e.EMP_CODE
where e.ACTIVE_STATUS == "A"
select new HRM_EMP_FINL_STMT_MSTModel
{
EMP_CODE = s.EMP_CODE,
EMP_NAME = e.EMP_NAME,
DIVI_CODE = e.DIVI_CODE,
DIVI_NAME = e.DIVI_NAME,
EMP_DESIG_CODE = e.EMP_DESIG_CODE,
EMP_DESIG_NAME = e.EMP_DESIG_NAME,
JOINING_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(e.JOINING_DATE)),
TRMN_TYPE = HRMD_COMMON.ReturnTerminationType(s.TRMN_TYPE),
TRMN_EFCT_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(s.TRMN_EFCT_DATE)),
LAST_SAL_PROS_MON = HRMD_COMMON.ReturnMonthName(s.LAST_SAL_PROS_MON),
FINL_STMT_REM = s.TRMN_REM
}).ToList();
var ConfirmedEmployees = (from c in DataContext.HRM_EMP_FINL_STMT_MST.AsEnumerable()
where ((Convert.ToDateTime(c.FINL_STMT_DATE)).Year).ToString() == Year && ((Convert.ToDateTime(c.FINL_STMT_DATE)).Month).ToString() == HRMD_COMMON.ReturnMonthName(Month)
join e in DataContext.VW_HRM_EMPLOYEE on c.EMP_CODE equals e.EMP_CODE
join s in DataContext.HRM_EMP_TRMN on c.EMP_CODE equals s.EMP_CODE
select new HRM_EMP_FINL_STMT_MSTModel
{
EMP_CODE = s.EMP_CODE,
EMP_NAME = e.EMP_NAME,
DIVI_CODE = e.DIVI_CODE,
DIVI_NAME = e.DIVI_NAME,
EMP_DESIG_CODE = e.EMP_DESIG_CODE,
EMP_DESIG_NAME = e.EMP_DESIG_NAME,
JOINING_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(e.JOINING_DATE)),
TRMN_TYPE = HRMD_COMMON.ReturnTerminationType(s.TRMN_TYPE),
TRMN_EFCT_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(s.TRMN_EFCT_DATE)),
LAST_SAL_PROS_MON = HRMD_COMMON.ReturnMonthName(s.LAST_SAL_PROS_MON),
FINL_STMT_REM = s.TRMN_REM
}).ToList();
Tyring to remove the items from the first list, which are also in second list.
var FinalSeparatedEmployees = (from item in SeparatedEmployees
where !ConfirmedEmployees.Contains(item)
select item).ToList();
Tried this one too:
FinalSeparatedEmployees = SeparatedEmployees.Except(ConfirmedEmployees).ToList<HRM_EMP_FINL_STMT_MSTModel>();
But not getting the accurate result. What I'm missing? Thanks.
Its better to use EMP_CODE because your objects are not comparable.
var ids = ConfirmedEmployees.Select(x => x.EMP_CODE).ToList();
var FinalSeparatedEmployees = (from item in SeparatedEmployees
where !ids.Contains(item.EMP_CODE)
select item).ToList();
I have two queries that I need to combine in LINQ that both actually come from the same table. The reason for this is that one of the queries needs to get the max of a field for each day and then sum the days together where the second query can just sum everything right off the bat. Here is the first query:
var queryDownload = from p in
(from p in almdbContext.cl_contact_event
where p.time_of_contact >= startDate && p.time_of_contact < endDate && p.input_file_name.Contains(inputFileName) && listName.Contains(listName)
group p by new
{
date = EntityFunctions.CreateDateTime(p.time_of_contact.Value.Year, p.time_of_contact.Value.Month, p.time_of_contact.Value.Day, 0, 0, 0),
listName = p.contact_list_name
} into g
select new
{
date = g.Key.date,
listName = g.Key.listName,
download = g.Max(a => a.total_number_of_records)
})
group p by p.listName into g
select new
{
listName = g.Key,
totalDownload = g.Sum(a => a.download),
};
This is the second:
var queryPenData = from p in almdbContext.cl_contact_event
where p.time_of_contact >= startDate && p.time_of_contact < endDate && p.input_file_name.Contains(inputFileName) && listName.Contains(listName)
group p by p.contact_list_name into g
select new
{
listName = g.Key,
dials = g.Sum(a => a.ov_dial_start_time != null ? 1 : 0),
agentConnects = g.Sum(a => a.agent_login_name != null ? 1 : 0),
abandons = g.Sum(a => a.response_status == "DAC" || a.response_status == "DAD" ? 1 : 0),
rightPartyContacts = g.Sum(a => a.response_status == "PTP" || a.response_status == "RPC" ? 1 : 0),
promiseToPays = g.Sum(a => a.response_status == "PTP" ? 1 : 0),
talkTime = g.Sum(a => EntityFunctions.DiffSeconds(a.ov_call_connected_time, a.ov_trunk_released_time)) ?? 0,
wrapTime = g.Sum(a => EntityFunctions.DiffSeconds(a.ov_trunk_released_time, a.record_released_time)) ?? 0
};
And this is the query joining them together.
var queryJoin = from qd in queryDownload
join qp in queryPenData
on qd.listName equals qp.listName
select new
{
listName = qp.listName,
download = qd.totalDownload,
dials = qp.dials,
agentConnects = qp.agentConnects,
abandons = qp.abandons,
rightPartyContacts = qp.rightPartyContacts,
promiseToPays = qp.promiseToPays,
talkTime = qp.talkTime,
wrapTime = qp.wrapTime
};
This seems extremely verbose/roundabout to me. Is there a better way I can write/approach this to shrink/simplify the code?
For your last query could you not just do something like this?
var queryJoin = from qd in queryDownload join qpd in queryPenData on qd.listname equals qpd....
Should be able to do this:
var queryJoin = from qd in queryDownload
join qp in queryPenData
on qd.listName equals qp.listName
select new
{
qp, qd
};
From what I can tell you've already formed your data in queryPenData so there is no reason to re-assign it to new variables in the final join. Just select the object which will allow you to traverse into the anonymous type in queryPenData. I think...