Using Any to check against a list in NHibernate - asp.net-mvc-3

I am trying to get all #events where that have a FiscalYear.id inIList<int> years. I am using any() but it is throwing the following stacktrace error:
Unrecognised method call:
System.Linq.Enumerable:Boolean Any[TSource](System.Collections.Generic.IEnumerable`1[TSource], System.Func`2[TSource,System.Boolean])
Any Ideas? Here is the code:
FindAllPaged(int eventTypeId, IList<int> aors, IList<int> years)
{
IList<Domain.Event> results =
session.QueryOver<Event>()
.Where(#event => !#event.IsDeleted &&
#event.EventType.Id == eventTypeId &&
years.Any(y => y == #event.FiscalYear.Id))
}

Looks like you are trying to use a Linq method in QueryOver. This isn't supported. Try using the Linq provider instead:
FindAllPaged(int eventTypeId, IList<int> aors, IList<int> years)
{
IList<Domain.Event> results =
session.Query<Event>()
.Where(#event => !#event.IsDeleted &&
#event.EventType.Id == eventTypeId &&
years.Any(y => y == #event.FiscalYear.Id))
}

I also encountered the same exception message
Unrecognised method call:
System.Linq.Enumerable:Boolean Any[TSource](System.Collections.Generic.IEnumerable1[TSource], System.Func2[TSource,System.Boolean])
when using IqueryOver with Contains method
Ex:
var departmentTypesArray = criteria.DepartmentTypes.ToArray();
qover = qover.Where(p => departmentTypesArray.Contains(p.DepartmentType));
when i check the database, i don't have any records inside the table that i am making query.
when i changed my query with Restrictions, then it works for me
qover = qover.WhereRestrictionOn(p => .DepartmentType).IsIn(departmentTypesArray);

Try using the Contains method instead:
IList<Domain.Event> results = session
.QueryOver<Event>()
.Where(e => !#event.IsDeleted &&
#event.EventType.Id == eventTypeId &&
years.Contains(#event.FiscalYear.Id))
.ToList();
Or build your restrictions the long way using IsIn:
IList<Domain.Event> results = session
.QueryOver<Event>()
.Where(e => !#event.IsDeleted && #event.EventType.Id == eventTypeId)
.And(Restrictions.On<Event>(#event => #event.FiscalYear.Id)
.IsIn(years.ToArray()))
.ToList();

You could try this:
IList<Domain.Event> results = session.QueryOver<Event>().ToList().FindAll(e => !e.IsDeleted && e.Id.Equals(eventTypeId) && years.Contains(e.FiscalYear.Id))

Related

Is it possible to use Linq with LazyCache

I hope you are well. Is it possible to query the LazyCache cache using Linq?
// Initialize Class
retVal = (ModelXyz)MemoryCache.Default.Where(u => (u.Value is ModelXyz) &&
(u.Value as ModelXyz).Property1 == abc &&
(u.Value as ModelXyz).Property2 == cde &&
(u.Value as ModelXyz).Property3 == true).Select(x => x.Value).FirstOrDefault();

Linq join with exists

I'm busy rewriting a system and are using Linq queries to extract data from the database. I am used to plain old TSQL and stored procedures so my Linq skills are not the best.
I have a sql query that I try to rewrite in Linq that contains a join, where clause and IN statements. I do get it right but when I run the sql query I get a different value as from the Linq query. Somewhere I'm missing something and can't find the reason.
Here is the SQL:
select
isnull(Sum(QtyCC) + Sum(QtyEmployee), 0) *
isnull(Sum(UnitPrice), 0)[TotalRValue]
from
tbl_app_KGCWIssueLines a
inner join tbl_app_KGCWIssue b on b.IssueNrLnk = a.IssueNrLnk
where
b.CreationDate >= '2011-02-01' and
a.IssueNrLnk IN (
select
IssueNrLnk
from
tbl_app_KGCWIssue
where
CustomerCode = 'PRO002' and
ISNULL(Tier1,'') = 'PRO002' and
ISNULL(Tier2,'') = 'HAMD01' and
ISNULL(Tier3,'') = '02' and
ISNULL(Tier4,'') = '02001' and
ISNULL(Tier5,'') = 'PTAHQ001' and
ISNULL(Tier6,'') = '035' and
ISNULL(Tier7,'') = '' and
ISNULL(Tier8,'') = '' and
ISNULL(Tier9,'') = '' and
ISNULL(Tier10,'') = ''
)
And here is the Linq:
ctx.ObjectContext.tbl_app_KGCWIssue
.Join(ctx.ObjectContext.tbl_app_KGCWIssueLines,
i => i.IssueNrLnk, l => l.IssueNrLnk, (i, l) => new { i, l })
.Where(o => o.i.CreationDate >= IntervalStartDate)
.Where(p => ctx.ObjectContext.tbl_app_KGCWIssue
.Where(a =>
a.CustomerCode == CustomerCode &&
a.Tier1 == employee.Tier1 &&
a.Tier2 == employee.Tier2 &&
a.Tier3 == employee.Tier3 &&
a.Tier4 == employee.Tier4 &&
a.Tier5 == employee.Tier5 &&
a.Tier6 == employee.Tier6 &&
a.Tier7 == employee.Tier7 &&
a.Tier8 == employee.Tier8 &&
a.Tier9 == employee.Tier9 &&
a.Tier10 == employee.Tier10)
.Select(i => i.IssueNrLnk)
.Contains(p.l.IssueNrLnk))
.Sum(p => p.l.UnitPrice * (p.l.QtyEmployee + p.l.QtyCC));

LINQ Performance Issue on only a few hundred records

in the following code i've commented on the line that SLOWS my page right down. I did some speed test to reveal the CONTAINS LINQ expression is the problem.
Does anyone know how to change this one line to be more efficient using something else instead. I'm also curious as to why its so slow.
Any ideas (thanks in advance):
var allWaste = _securityRepository.FindAllWaste(userId, SystemType.W);
var allWasteIndicatorItems = _securityRepository.FindAllWasteIndicatorItems();
// First get all WASTE RECORDS
var searchResults = (from s in allWaste
join x in allWasteIndicatorItems on s.WasteId equals x.WasteId
where (s.Description.Contains(searchText)
&& s.Site.SiteDescription.EndsWith(searchTextSite)
&& (s.CollectedDate >= startDate && s.CollectedDate <= endDate))
&& x.EWC.EndsWith(searchTextEWC)
select s).Distinct();
var results = searchResults.AsEnumerable();
if (hazardous != "-1")
{
// User has requested to filter on Hazardous or Non Hazardous only rather than Show All
var HazardousBoolFiltered = (from we in _db.WasteIndicatorItems
.Join(_db.WasteIndicators, wii => wii.WasteIndicatorId, wi => wi.WasteIndicatorId, (wii, wi) => new { wasteid = wii.WasteId, wasteindicatorid = wii.WasteIndicatorId, hazardtypeid = wi.HazardTypeId })
.Join(_db.HazardTypes, w => w.hazardtypeid, h => h.HazardTypeId, (w, h) => new { wasteid = w.wasteid, hazardous = h.Hazardous })
.GroupBy(g => new { g.wasteid, g.hazardous })
.Where(g => g.Key.hazardous == true && g.Count() >= 1)
select we).AsEnumerable(); // THIS IS FAST
// Now join the 2 object to eliminate all the keys that do not apply
if (bHazardous)
results = (from r in results join x in HazardousBoolFiltered on r.WasteId equals x.Key.wasteid select r).AsEnumerable(); //This is FAST
else
results = (from r in results.Where(x => !HazardousBoolFiltered
.Select(y => y.Key.wasteid).Contains(x.WasteId)) select r).AsEnumerable(); // This is DOG SLOW 10-15 seconds !--- THIS IS SLOWING EXECUTION by 10 times --!
}
return results.AsQueryable();
I suggest using a logging / tracing framework like smart inspect or log4net combined with a debug text writer.
http://www.codesprouts.com/post/View-LINQ-To-SQL-Statements-Using-A-Debug-TextWriter.aspx
another possibility is to use the sql server profiler and see what sql linq2sql produces.
also a very nice way is to use the mvc mini profiler in combination with the Profiled DB Connection and the SqlFormatters.SqlServerFormatter.
Try Any (MSDN)
Try this:
results = (from r in results
.Where(x => !HazardousBoolFiltered
.Any(y => y.Key.wasteid == r.WasteId)))
.AsEnumerable()
Or Count:
results = (from r in results
.Where(x => HazardousBoolFiltered
.Count(y => y.Key.wasteid == r.WasteId) == 0))
.AsEnumerable()

Error trying to exclude records with a JOIN to another object

In my code below, is there any way I can use the results in the object 'WasteRecordsExcluded' to join with searchResults, essentially excluding the WasteId's I don't want.
If I debug to the last line I get the error :
base {System.SystemException} = {"The query contains references to items defined on a different data context."}
Or if joining is impossible then i could change bHazardous from TRUE to FALSE and FALSE to TRUE and do some kind of 'NOT IN' comparison.
Going bananas with this one, anyone help? Kind Regards :
var allWaste = _securityRepository.FindAllWaste(userId, SystemType.W);
var allWasteIndicatorItems = _securityRepository.FindAllWasteIndicatorItems();
// First get all WASTE RECORDS
var searchResults = (from s in allWaste
join x in allWasteIndicatorItems on s.WasteId equals x.WasteId
where (s.Description.Contains(searchText)
&& s.Site.SiteDescription.EndsWith(searchTextSite)
&& (s.CollectedDate >= startDate && s.CollectedDate <= endDate))
&& x.EWC.EndsWith(searchTextEWC)
select s).Distinct();
var results = searchResults;
if (hazardous != "-1")
{
// User has requested to filter on Hazardous or Non Hazardous only rather than Show All
var WasteRecordsExcluded = (from we in _db.WasteIndicatorItems
.Join(_db.WasteIndicators, wii => wii.WasteIndicatorId, wi => wi.WasteIndicatorId, (wii, wi) => new { wasteid = wii.WasteId, wasteindicatorid = wii.WasteIndicatorId, hazardtypeid = wi.HazardTypeId })
.Join(_db.HazardTypes, w => w.hazardtypeid, h => h.HazardTypeId, (w, h) => new { wasteid = w.wasteid, hazardous = h.Hazardous })
.GroupBy(g => new { g.wasteid, g.hazardous })
.Where(g => g.Key.hazardous == bHazardous && g.Count() >= 1)
select we);
// Now join the 2 object to eliminate all the keys that do not apply
results = results.Where(n => WasteRecordsExcluded.All(t2 => n.WasteId == t2.Key.wasteid));
}
return results;
Maybe something like this:
.....
var results = searchResults.ToList();
.....
.....
.Where(g => g.Key.hazardous == bHazardous && g.Count() >= 1)
select we).ToList();
.....

Consecutive (conditional) Where clauses in Linq

I'm trying to construct a Linq statement to be used from a client with the Sharepoint (2010) object model.
This is the problematic piece of code:
var result = news.Where(n => (bool)n["Online"]
&& ((DateTime)n["StartDate"] <= DateTime.Now && (DateTime)n["StopDate"] >= DateTime.Now));
if (currentUser.IsAgUser())
result = result.Where(n => (string)n["Role"] != "AG-ADMIN");
var filteredNews = sharepointContext.LoadQuery(result);
When the if parte is executed and so another Where is added to result, I get the followin error when LoadQuerying it.
The query expression 'value(Microsoft.SharePoint.Client.ListItemCollection).Where(n => (Convert(n.get_Item("Online")) AndAlso ((Convert(n.get_Item("StartDate")) <= DateTime.Now) AndAlso (Convert(n.get_Item("StopDate")) >= DateTime.Now)))).Where(n => (Convert(n.get_Item("Role")) != "AG-ADMIN"))' is not supported.
Where is the error coming from? Thanks
It seems like SharePoint doesn't support several wheres.
Cheap solution:
var result = currentUser.IsAgUser()
? news.Where(n => (bool)n["Online"]
&& ((DateTime)n["StartDate"] <= DateTime.Now && (DateTime)n["StopDate"] >= DateTime.Now) && (string)n["Role"] != "AG-ADMIN")
: news.Where(n => (bool)n["Online"]
&& ((DateTime)n["StartDate"] <= DateTime.Now && (DateTime)n["StopDate"] >= DateTime.Now));
var filteredNews = sharepointContext.LoadQuery(result);

Resources