how to use Linq to get a sitecore field - c#

I have a search that I'm wanting to exclude any search result that has the name of the "Title" field in the search. For example, say I type in "Contact" in the search bar. I don't want the Contact Us page to come up, but if someone wants to search something that has words in the Contact Us page, then its ok. I am able to get templateName and IDs but can't seem to get fields...
Item homeItem = Main.Utilities.SitecoreUtils.getHomeItem();
var query = PredicateBuilder.True<SearchResultItem>();
query = query.And(i => i.Paths.Contains(homeItem.ID));
query = query.And(i => i.Content.Contains(searchTerm));
query = query.And(i => i.TemplateName != "MenuFolder");
This is what I have, but I want to add something to it to exclude the "Title" field and maybe the "SEO" field. So probably something like:
query = query.And(i => i.Fields["Title"];
But in this case its including not excluding it. And I can't do:
query = query.And(i != i.Fields["Title"];
It won't accept that answer.

Try to use code like that i => !i["Title"].Contains(searchTerm):
Item homeItem = Main.Utilities.SitecoreUtils.getHomeItem();
var query = PredicateBuilder.True<SearchResultItem>();
query = query.And(i => i.Paths.Contains(homeItem.ID));
query = query.And(i => i.Content.Contains(searchTerm));
query = query.And(i => i.TemplateName != "MenuFolder");
query = query.And(i => !i["Title"].Contains(searchTerm));

If you want to strongly type it, you just need to extend the SearchResultItem class with your field name.
public class SitecoreItem : SearchResultItem
{
[IndexField("title")]
public string Title { get; set; }
[IndexField("__smallcreateddate")]
public DateTime PublishDate { get; set; }
[IndexField("has_presentation")]
public bool HasPresentation { get; set; }
}
Then your code would be like this
IQueryable<SitecoreItem> query = context.GetQueryable<SitecoreItem>();
SearchResults<SitecoreItem> results = null;
query = query.Where(x => x.Title.Contains(searchText);
results = query.GetResults();

Related

dynamically define key name for which the value needs to be identified

I have a keyvalue pair list some thing like this
List<Subscriptions> subs = new List<Subscriptions>();
subs.Add(new Subscriptions() { Id = 1, Name = "ABC" });
subs.Add(new Subscriptions() { Id = 1, Name = "DEF" });
I can search against one key (ID or Name) but what I want to achieve is that user define which key they want to search against ID or Name
right now i am using this approach to filter the list based on Name Value
var filtered = subs.Where(sub => sub.Name.IndexOf(SearchString.Text,StringComparison.OrdinalIgnoreCase) >=0);
sub.Name is defined statically here, I want the user to choose what they want their search to be based on
for example if we have abc:Name program search for abc under Name key and if we have 1:Id then it search for 1 in ID.
This is just an example , in real scenario i can have multiple fields in my list.
I hope I am able to make myself clear.
Why you don't apply the Where by an simple if else or switch
// keyword : abc:Name or 1:Id
var value = keyword.Split(':')[0];
var key = keyword.Split(':')[1];
if(key == "Name")
{
var filterred = subs.Where(sub => sub.Name == value);
}
else if(key == "Id")
var filterred = subs.Where(sub => sub.id == int.Parse(value));
}
Fast answer:
string name = "";
int? id = null;
List<Subscriptions> subs = new List<Subscriptions>();
var query = subs.AsQueryable();
if (!string.IsNullOrEmpty(name))
query = query.Where(p => p.Name == name);
if (id.HasValue)
query = query.Where(p => p.id == id.Value);
var result = query.ToArray();
Detailed answer: you can read about expression tree and IQueryable interface
Basically you can avoid to cast your list to IQueryable if you not use something like Entity Frmework or OData. But if you need to convert you LINQ expression to something more complex - you should use IQueryable, or build your own expression tree.

BaseQuery class missing in new NEST dll version NEST.1.1.2

What is the replacement of BaseQuery class in new version.
I couldn't find it anywhere.
My problem is how to generate syntax in c# for the search criteria as:
public class TextSearch
{
public string Headline {get;set;}
public string Summary {get;set;}
}
I need to search using text 'you', against two column as OR operator, Column 1 summary and Column 2 headline.
Earlier I was doing,
var orQuery = new List<BaseQuery>();
if (!string.IsNullOrEmpty(searchtext))
{
orQuery .Add(Query<TextSearch>.Terms("headline", searchOptions.text.ToLower().Split(' ')));
orQuery .Add(Query<TextSearch>.Terms("summary", searchOptions.text.ToLower().Split(' ')));
}
var finalQuery = new List<BaseQuery>();
finalQuery .Add(Query<TextSearch>.Bool(o => o.Should(orQuery.ToArray())));
Now this doesn't work.
Is there any better syntax for searching in new version.
The search criteria should using LIKE with OR,
e.g. summary LIKE '%you%' OR headling LIKE '%you%'
The documentation on the breaking changes in NEST 1.0 is pretty complete:
http://nest.azurewebsites.net/breaking-changes.html
We renamed BaseQuery to QueryContainer
The query can be:
client.Search<TextSearch>(s=>s
.Query(q=>
q.Terms("headline", words)
|| q.Terms("summary", words)
)
)
If words is empty or null that part is not rendered see the conditionless query section here:
http://nest.azurewebsites.net/nest/writing-queries.html
#Martijn Laarman
Since we have numerous filter criteria that will be dynamic based on user selected filter,
I'm constructing Filter Query in amethod based on user slelcted filter and then pass it to Search<> method as:
QueryContainer mainQuery = null;
if (!string.IsNullOrEmpty(searchOptions.SearchText))
{
var headline = Query<T>.Terms("headline", searchOptions.Headline.ToLower());
var summary = Query<T>.Terms("fullSummary", searchOptions.Summary.ToLower());
mainQuery &= (headline || summary);
}
if (searchOptions.FromDate != DateTime.MinValue && searchOptions.ToDate != DateTime.MinValue)
{
var dateFilter = Query<T>.Range(
r => r.OnField("processedDate").GreaterOrEquals(searchOptions.FromDate, ElasticDateFormat).LowerOrEquals(searchOptions.ToDate, ElasticDateFormat));
mainQuery &= dateFilter;
}
var result = Client.Search<T>(s => s.Query(mainQuery ).Size(Int32.MaxValue));
Here Client is a property that returns ElasticClient object.
Hope thats the correct way of doing.

Passing parameter to LINQ query

I have a method like below:
public void GetUserIdByCode(string userCode)
{
var query = from u in db.Users
where u.Code == userCode // userCode = "LRAZAK"
select u.Id;
var userId = query.FirstOrDefault(); // userId = 0 :(
}
When I ran the code, I got the default value of 0 assigned to userId meaning the Id was not found.
However, if I changed the userCode with a string like below, I will get the value I want.
public void GetUserIdByCode(string userCode)
{
var query = from u in db.Users
where u.Code == "LRAZAK" // Hard-coded string into the query
select u.Id;
var userId = query.FirstOrDefault(); // userId = 123 Happy days!!
}
My question is why passing the parameter into the LINQ query does not work?
When I stepped into the code, I got the SQL statement like so:
// Does not work...
{SELECT "Extent1"."LOGONNO" AS "LOGONNO"FROM "DEBTORSLIVE"."DEBTORS_LOGONS" "Extent1"WHERE ("Extent1"."LOGONCODE" = :p__linq__0)}
The hard-coded LINQ query (the working one) gives an SQL statement as below:
// Working just fine
{SELECT "Extent1"."LOGONNO" AS "LOGONNO"FROM "DEBTORSLIVE"."DEBTORS_LOGONS" "Extent1"WHERE ('LRAZAK' = "Extent1"."LOGONCODE")}
What would be the solution?
As a work-around, I use Dynamic Linq.
The code below is working for me.
public void GetUserIdByCode(string userCode)
{
string clause = String.Format("Code=\"{0}\"", userCode);
var userId = db.Users
.Where(clause)
.Select(u => u.Id)
.FirstOrDefault();
}
The database query returns an object of User with Code and Id as properties. This is defined in one of my classes.
Here is syntax that will work to pass an argument to a LINQ query.
Not sure how many people will be searching this topic so many years later, but here's a code example that gets the job done:
string cuties = "777";
// string collection
IList<string> stringList = new List<string>() {
"eg. 1",
"ie LAMBDA",
"777"
};
var result = from s in stringList
where (s == cuties)
select s;
foreach (var str in result)
{
Console.WriteLine(str); // Output: "777"
}

Querying 2 Sets of Complex-Objects Using Linq

I have two lists comprised of different complex-objects, and each one is from 2 separate data-sources. One list may-or-may-not contain records. When any records exist in the "optional" list I need the "normal" list to be further-filtered.
Unfortunately, I can only find very simple examples here and online, which is why I am asking this question.
The Pseudo-Logic Goes Like This:
When QuickFindMaterial records exist, get all DataSource records where query.Name is in the QuickFindMaterial.Material collection. If no QuickFindMaterial records exist do not affect the final result. Lastly, select all distinct DataSourcerecords.
The Classes Looks Like:
public class QuickFindMaterial
{
public string SiteId { get; set; }
public string Material { get; set; }
}
The Code Looks Like:
I have commented-out my failed WHERE logic below
var dataSource = DocumentCollectionService.ListQuickFind();
var quickFindMaterial = ListMaterialBySiteID(customerSiteId);
var distinct = (from query in dataSource
select new
{
ID = query.DocumentID,
Library = query.DocumentLibrary,
ModifiedDate = query.DocumentModifiedDate,
Name = query.DocumentName,
Title = query.DocumentTitle,
Type = query.DocumentType,
Url = query.DocumentUrl,
})
//.Where(x => x.Name.Contains(quickFindMaterial.SelectMany(q => q.Material)))
//.Where(x => quickFindMaterial.Contains(x.Name))
.Distinct();
I think this is what you want:
.Where(x => !quickFindMaterial.Any() || quickFindMaterial.Any(y => x.Name == y.Material))
You could join on Name -> Material
Example:
var distinct = (from query in dataSource
join foo in quickFindMaterial on query.Name equals foo.Material
select new
{
ID = query.DocumentID,
Library = query.DocumentLibrary,
ModifiedDate = query.DocumentModifiedDate,
Name = query.DocumentName,
Title = query.DocumentTitle,
Type = query.DocumentType,
Url = query.DocumentUrl,
}).Distinct();

Join/Where with LINQ and Lambda

I'm having trouble with a query written in LINQ and Lambda. So far, I'm getting a lot of errors here's my code:
int id = 1;
var query = database.Posts.Join(database.Post_Metas,
post => database.Posts.Where(x => x.ID == id),
meta => database.Post_Metas.Where(x => x.Post_ID == id),
(post, meta) => new { Post = post, Meta = meta });
I'm not sure if this query is correct.
I find that if you're familiar with SQL syntax, using the LINQ query syntax is much clearer, more natural, and makes it easier to spot errors:
var id = 1;
var query =
from post in database.Posts
join meta in database.Post_Metas on post.ID equals meta.Post_ID
where post.ID == id
select new { Post = post, Meta = meta };
If you're really stuck on using lambdas though, your syntax is quite a bit off. Here's the same query, using the LINQ extension methods:
var id = 1;
var query = database.Posts // your starting point - table in the "from" statement
.Join(database.Post_Metas, // the source table of the inner join
post => post.ID, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
meta => meta.Post_ID, // Select the foreign key (the second part of the "on" clause)
(post, meta) => new { Post = post, Meta = meta }) // selection
.Where(postAndMeta => postAndMeta.Post.ID == id); // where statement
You could go two ways with this. Using LINQPad (invaluable if you're new to LINQ) and a dummy database, I built the following queries:
Posts.Join(
Post_metas,
post => post.Post_id,
meta => meta.Post_id,
(post, meta) => new { Post = post, Meta = meta }
)
or
from p in Posts
join pm in Post_metas on p.Post_id equals pm.Post_id
select new { Post = p, Meta = pm }
In this particular case, I think the LINQ syntax is cleaner (I change between the two depending upon which is easiest to read).
The thing I'd like to point out though is that if you have appropriate foreign keys in your database, (between post and post_meta) then you probably don't need an explicit join unless you're trying to load a large number of records. Your example seems to indicate that you are trying to load a single post and its metadata. Assuming that there are many post_meta records for each post, then you could do the following:
var post = Posts.Single(p => p.ID == 1);
var metas = post.Post_metas.ToList();
If you want to avoid the n+1 problem, then you can explicitly tell LINQ to SQL to load all of the related items in one go (although this may be an advanced topic for when you're more familiar with L2S). The example below says "when you load a Post, also load all of its records associated with it via the foreign key represented by the 'Post_metas' property":
var dataLoadOptions = new DataLoadOptions();
dataLoadOptions.LoadWith<Post>(p => p.Post_metas);
var dataContext = new MyDataContext();
dataContext.LoadOptions = dataLoadOptions;
var post = Posts.Single(p => p.ID == 1); // Post_metas loaded automagically
It is possible to make many LoadWith calls on a single set of DataLoadOptions for the same type, or many different types. If you do this lots though, you might just want to consider caching.
Daniel has a good explanation of the syntax relationships, but I put this document together for my team in order to make it a little simpler for them to understand. Hope this helps someone
Your key selectors are incorrect. They should take an object of the type of the table in question and return the key to use in the join. I think you mean this:
var query = database.Posts.Join(database.Post_Metas,
post => post.ID,
meta => meta.Post_ID,
(post, meta) => new { Post = post, Meta = meta });
You can apply the where clause afterwards, not as part of the key selector.
Posting because when I started LINQ + EntityFramework, I stared at these examples for a day.
If you are using EntityFramework, and you have a navigation property named Meta on your Post model object set up, this is dirt easy. If you're using entity and don't have that navigation property, what are you waiting for?
database
.Posts
.Where(post => post.ID == id)
.Select(post => new { post, post.Meta });
If you're doing code first, you'd set up the property thusly:
class Post {
[Key]
public int ID {get; set}
public int MetaID { get; set; }
public virtual Meta Meta {get; set;}
}
I've done something like this;
var certificationClass = _db.INDIVIDUALLICENSEs
.Join(_db.INDLICENSECLAsses,
IL => IL.LICENSE_CLASS,
ILC => ILC.NAME,
(IL, ILC) => new { INDIVIDUALLICENSE = IL, INDLICENSECLAsse = ILC })
.Where(o =>
o.INDIVIDUALLICENSE.GLOBALENTITYID == "ABC" &&
o.INDIVIDUALLICENSE.LICENSE_TYPE == "ABC")
.Select(t => new
{
value = t.PSP_INDLICENSECLAsse.ID,
name = t.PSP_INDIVIDUALLICENSE.LICENSE_CLASS,
})
.OrderBy(x => x.name);
It could be something like
var myvar = from a in context.MyEntity
join b in context.MyEntity2 on a.key equals b.key
select new { prop1 = a.prop1, prop2= b.prop1};
This linq query Should work for you. It will get all the posts that have post meta.
var query = database.Posts.Join(database.Post_Metas,
post => post.postId, // Primary Key
meta => meat.postId, // Foreign Key
(post, meta) => new { Post = post, Meta = meta });
Equivalent SQL Query
Select * FROM Posts P
INNER JOIN Post_Metas pm ON pm.postId=p.postId
Query Syntax for LINQ Join
var productOrderQuery = from product in Product.Setup()//outer sequence
join order in OrderDetails.Setup()//inner sequence
on product.Id equals order.ProductId //key selector
select new//result selector
{
OrderId = order.Id,
ProductId = product.Id,
PurchaseDate = order.PurchaseDate,
ProductName = product.Name,
ProductPrice = product.Price
};
Method Syntax for LINQ Join
var productOrderMethod = Product.Setup().//outer sequence
Join(OrderDetails.Setup(), //inner sequence
product => product.Id//key selector
,order=> order.ProductId //key selector
,(product,order)=> //projection result
new
{
OrderId = order.Id,
ProductId = product.Id,
PurchaseDate = order.PurchaseDate,
ProductName = product.Name,
ProductPrice = product.Price
}
);
Product.cs for reference
class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public static IEnumerable<Product> Setup()
{
return new List<Product>()
{
new Product(){Id=1, Name="Bike", Price=30.33M },
new Product(){Id=2, Name="Car", Price=50.33M },
new Product(){Id=3, Name="Bus", Price=60.33M }
};
}
}
OrderDetails.cs class for reference
class OrderDetails
{
public int Id { get; set; }
public virtual int ProductId { get; set; }
public DateTime PurchaseDate { get; set; }
public static IEnumerable<OrderDetails> Setup()
{
return new List<OrderDetails>()
{
new OrderDetails(){Id=1, ProductId=1, PurchaseDate= DateTime.Now },
new OrderDetails(){Id=2, ProductId=1, PurchaseDate=DateTime.Now.AddDays(-1) },
new OrderDetails(){Id=3, ProductId=2, PurchaseDate=DateTime.Now.AddDays(-2) }
};
}
}
1 equals 1 two different table join
var query = from post in database.Posts
join meta in database.Post_Metas on 1 equals 1
where post.ID == id
select new { Post = post, Meta = meta };

Categories