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();
I'm not sure if I'm barking up the wrong tree but I wanted to create a function to check if an account exists based on all optional parameters so it can be used to pull data depending on whatever you'd like to check on.
Basically the query should be:
where loginName = p1 or loginName = p2 or loginName = p3 but with the paramters all being optional, however at least one will be provided.
This is what I tried so far:
public async Task<bool> CheckAccountExistsAsync(string loginName = "", string authenticatorId = "", string eId = "")
{
if (string.IsNullOrWhiteSpace(loginName) && string.IsNullOrWhiteSpace(authenticatorId) && string.IsNullOrWhiteSpace(eId))
throw new InvalidOperationException("You must pass at least one parameter");
return await _context.Accounts.AnyAsync(a =>
(string.IsNullOrWhiteSpace(loginName) || a.LoginName == loginName)
|| (string.IsNullOrWhiteSpace(authenticatorId) || a.AuthenticatorId == authenticatorId)
|| (string.IsNullOrWhiteSpace(eId) || a.EmployeeId == eId));
}
Problem with this approach is that if I just pass the loginName, then the query is as follows with the condition completely omitted.:
SELECT CASE
WHEN EXISTS (
SELECT 1
FROM [Accounts] AS [a]) THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END
I'm sure I'm missing something, is there a better approach?
What you are using is applicable for optional and expressions, e.g.
return await _context.Accounts.AnyAsync(a =>
(string.IsNullOrWhiteSpace(loginName) || a.LoginName == loginName)
&& (string.IsNullOrWhiteSpace(authenticatorId) || a.AuthenticatorId == authenticatorId)
&& (string.IsNullOrWhiteSpace(eId) || a.EmployeeId == eId));
For optional or you have to use optional and sub conditions and add additional check for all optional parameters missing, e.g.
return await _context.Accounts.AnyAsync(a =>
(string.IsNullOrWhiteSpace(loginName)
&& string.IsNullOrWhiteSpace(authenticatorId)
&& string.IsNullOrWhiteSpace(eId))
|| (!string.IsNullOrWhiteSpace(loginName) && a.LoginName == loginName)
|| (!string.IsNullOrWhiteSpace(authenticatorId) && a.AuthenticatorId == authenticatorId)
|| (!string.IsNullOrWhiteSpace(eId) && a.EmployeeId == eId));
Update This may already be fixed: http://entityframework.codeplex.com/workitem/486
...
A fairly straightforward LINQ statement against my entities is resulting in unnecessarily complex SQL. More on that later, here's the setup:
Tables
Publication
PublicationId (pk)
TopicId (fk to a Topic table)
ReceiptCount (denormalized for query performance)
DateInserted
Receipt
ReceiptId (pk)
PublicationId (fk to the table above)
DateInserted
LINQ
var query = from r in context.Receipts.Include("Publication")
where r.DateInserted < lagDate
&& r.ReceiptId > request.AfterReceiptId
&& r.Publication.TopicId == topicEntity.TopicId
&& r.Publication.ReceiptCount > 1
select r;
SQL
exec sp_executesql N'SELECT TOP (25)
[Project1].[ReceiptId] AS [ReceiptId],
[Project1].[PublicationId] AS [PublicationId],
[Project1].[DateInserted] AS [DateInserted],
[Project1].[DateReceived] AS [DateReceived],
[Project1].[PublicationId1] AS [PublicationId1],
[Project1].[PayloadId] AS [PayloadId],
[Project1].[TopicId] AS [TopicId],
[Project1].[BrokerType] AS [BrokerType],
[Project1].[DateInserted1] AS [DateInserted1],
[Project1].[DateProcessed] AS [DateProcessed],
[Project1].[DateUpdated] AS [DateUpdated],
[Project1].[PublicationGuid] AS [PublicationGuid],
[Project1].[ReceiptCount] AS [ReceiptCount]
FROM ( SELECT
[Extent1].[ReceiptId] AS [ReceiptId],
[Extent1].[PublicationId] AS [PublicationId],
[Extent1].[DateInserted] AS [DateInserted],
[Extent1].[DateReceived] AS [DateReceived],
[Extent3].[PublicationId] AS [PublicationId1],
[Extent3].[PayloadId] AS [PayloadId],
[Extent3].[TopicId] AS [TopicId],
[Extent3].[BrokerType] AS [BrokerType],
[Extent3].[DateInserted] AS [DateInserted1],
[Extent3].[DateProcessed] AS [DateProcessed],
[Extent3].[DateUpdated] AS [DateUpdated],
[Extent3].[PublicationGuid] AS [PublicationGuid],
[Extent3].[ReceiptCount] AS [ReceiptCount]
FROM [dbo].[Receipt] AS [Extent1]
INNER JOIN [dbo].[Publication] AS [Extent2] ON [Extent1].[PublicationId] = [Extent2].[PublicationId]
LEFT OUTER JOIN [dbo].[Publication] AS [Extent3] ON [Extent1].[PublicationId] = [Extent3].[PublicationId]
WHERE ([Extent2].[ReceiptCount] > 1) AND ([Extent1].[DateInserted] < #p__linq__0) AND ([Extent1].[ReceiptId] > #p__linq__1) AND ([Extent2].[TopicId] = #p__linq__2)
) AS [Project1]
ORDER BY [Project1].[ReceiptId] ASC',N'#p__linq__0 datetime,#p__linq__1 int,#p__linq__2 int',#p__linq__0='2012-09-05 19:39:21:510',#p__linq__1=4458824,#p__linq__2=90
Problem
Publication gets joined twice:
LEFT OUTER JOIN because of .Include("Publication")
INNER JOIN because of the where.
If I remove [Extent2] from the SQL entirely, and change the WHERE bits to use [Extent3], I get the same results back. Since I'm not using Lazy Loading on my entities, I have to .Include("Publication")... is there any solution for this?
I was using EF4, but grabbed EF5 from NuGet to see if it was perhaps fixed, but it produces the same result (although I have no idea how to tell if my EDMX is really using EF5).
There is however, a work-around. It may not be the most elegant solution, but it does exactly what you want; it generates only one join.
Change:
var query = from r in context.Receipts.Include("Publication")
where r.DateInserted < lagDate
&& r.ReceiptId > request.AfterReceiptId
&& r.Publication.TopicId == topicEntity.TopicId
&& r.Publication.ReceiptCount > 1
select r;
To be:
var query = from r in context.Receipts
join pub in context.Publication on r.PublicationId equals pub.PublicationId
where r.DateInserted < lagDate
&& r.ReceiptId > request.AfterReceiptId
&& pub.TopicId == topicEntity.TopicId
&& pub.ReceiptCount > 1
select new {
Receipt = r,
Publication = pub
};
Note that we have removed the Include AND we are no longer using r.Publication.?? in the where clause. Instead we are using pub.??
Now when you loop through query, you will see that r.Publication is not null:
foreach ( var item in query)
{
//see that item.Publication is not null
if(item.Receipt != null && item.Receipt.Publication != null)
{
//do work based on a valid Publication
}
else
{
//do work based on no linked Publication
}
}
This behavior can be avoided by using temporary variables (eg, let pub = r.Publication).
var query = from r in context.Receipts
let pub = r.Publication // using a temp variable
where r.DateInserted < lagDate
&& r.ReceiptId > request.AfterReceiptId
&& pub.TopicId == topicEntity.TopicId
&& pub.ReceiptCount > 1
select new { r, pub };
I will optimize on previous person's answer by changing the code as below, which removes the need of join so you don't have to know what columns you need to join and also don't have to change LINQ when join criteria gets changed. This should have been unnecessary but MS is not focused on fixing their sql code generation right now.
var query = from pub in context.Publications
from r in pub.Reciepts
where r.DateInserted < lagDate
&& r.ReceiptId > request.AfterReceiptId
&& pub.TopicId == topicEntity.TopicId
&& pub.ReceiptCount > 1
select new {
Receipt = r,
Publication = pub
};
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);
I am trying to do a search with LINQ to NHibernate.
I have this code:
from d in rep.QueryAll<Document>()
where
d.Plata != null && d.Contractant != null && d.Stadiu == StadiuDocument.Polita
&& (d.NrPolita.Contains(query) ||
d.Contractant.CodUnic.Contains(query) ||
d.Contractant.Denumire.Contains(query) ||
d.Plata.IdTranzactie.Contains(query)) &&
((TipPolita != null) ? (d.Tip == (TipProdus)TipPolita) : (1 == 1)) &&
((StareDocument != null) ? (d.Stare == (StareDocument)StareDocument) : (1 == 1))
select new
{
The problem is that I have some select inputs that have general values. Something like this:
<select id="tippolita" >
<option value = "-1">Any value</option>
<option value = "1">Value 1</option>
<option value = "2">Value 2</option>
<option value = "3">Value 3</option>
</select>
So when "Any value" is selected the where statement should be true like I wrote here:
((TipPolita != null) ? (d.Tip == (TipProdus)TipPolita) : (1 == 1)) &&
((StareDocument != null) ? (d.Stare == (StareDocument)StareDocument) : (1 == 1))
This is almost the same as what I would write in SQL.
An error occurs inside the Nhibernate source code at line 33 in the file "Linq\NHLinqExpression.cs"
_expression = PartialEvaluatingExpressionTreeVisitor.EvaluateIndependentSubtrees(expression);
This error actually comes from the re-linq library.
One obvious workaround is to just write 3 if statements and put the appropriate LINQ queries in each of them but that means writing a lot more code.
Is there any way to make this kind of query work without copy-pasting the entire query and modifying just a little of it?
P.S.
This is the inner exception:
InnerException: System.NullReferenceException
Message=Object reference not set to an instance of an object.
Source=Anonymously Hosted DynamicMethods Assembly
StackTrace:
at lambda_method(Closure
)
I would rewrite this:
((TipPolita != null) ? (d.Tip == (TipProdus)TipPolita) : (1 == 1)) &&
((StareDocument != null) ? (d.Stare == (StareDocument)StareDocument) : (1 == 1))
as
(TipPolita == null || d.Tip == (TipProdus)TipPolita) &&
(StareDocument == null || d.Stare == (StareDocument)StareDocument)
I don't know whether it'll work in NHibernate or not, but it's more idiomatic C# at least, so I would expect that it's more likely to be supported.
As an alternative, you could just replace "1 == 1" with "true".
Well, figured out how to do this the proper way
var date = rep.QueryAll<Document>().Where(d => d.Plata != null && d.Contractant != null && d.Stadiu == StadiuDocument.Polita);
if (!string.IsNullOrEmpty(query))
date = date.Where(d => (d.NrPolita.Contains(query) ||
d.Contractant.CodUnic.Contains(query) ||
d.Contractant.Denumire.Contains(query)));
I just move the ifs into the code and build the query(or rather the IQueryable) bit by bit