OrderBy used with LINQ returns no rows in DOcumentDb - linq

I have been trying to use OrderBy in LINQ i have changed several fields but it always returns null (no rows) while my documents are present in the collection.
Here's my simple query-
var rests = _client.CreateDocumentQuery<Restraunt>(_collectionUri)
.OrderBy(x => x.RestName);

You have to create an indexing policy with a range index on the type of the property you use in the order by (here I assume a string).
If you let the default policy, the order by return no result.
You need a sorting policy like that :
restrauntsCollection.IndexingPolicy.IncludedPaths.Add(
new IncludedPath {
Path = "/RestName/?",
Indexes = new Collection<Index> {
new RangeIndex(DataType.String) { Precision = -1 } }
});
See this page for more information: https://azure.microsoft.com/en-us/documentation/articles/documentdb-orderby/
Hope this helps

Related

LINQ to SQL . how to select all record using .take()

var result=(from refridgerators in context.A
group refridgerators by new { refridgerators.Id, refridgerators.Name } into gr
select new DAO<String>
{
Key = gr.Key.Name,
Count = gr.Count()
}).OrderByDescending(k => k.Count).Take(numberOfRecords).ToList();
This is my linq to sql query this is working perfectly fine.
this shows top 5 records (sorted by their count) if i pass numberOfRecords =5.
now my problem is i don`t want to modify query. so what should i do in above query to show all records. This is in relation with my requirement i want to use same query to show all refridgerators and Top 5 , top 10 refridgerators.
I am not sure if it is possible using LINQ. but i guess there must be something related to this.
I would simply don't add the Take to the query but to the code where you consume this query.
So for example:
public static IEnumerable<DAO> GetRefrigerators()
{
var query = from refridgerators in context.A
group refridgerators by new { refridgerators.Id, refridgerators.Name } into gr
select new DAO<String>
{
Key = gr.Key.Name,
Count = gr.Count()
};
return query.OrderByDescending(k => k.Count);
}
Now you can either use:
var refrigerators = GetRefrigerators().Take(5).ToList();
or
var refrigerators = GetRefrigerators().Take(10).ToList();
or
var refrigerators = GetRefrigerators().ToList();
I'd make numberOfRecords a int? and if the value is null you should not call Take(numberOfRecords)
var result = (from refridgerators in context.A
group refridgerators by new { refridgerators.Id, refridgerators.Name } into gr
select new DAO<String>
{
Key = gr.Key.Name,
Count = gr.Count()
}).OrderByDescending(k => k.Count);
if(numberOfRecords.HasValue)
result = result.Take(numberOfRecords.Value);
return result.ToList();
I know it changes your query a little bit but I believe it is pretty acceptable, adding a numberOfRecords of a super high value adds an overheard to your query which isn't useful in your case.
So this post is very old, I know, but my solution is not provided (maybe someone wants to achieve the same after 2 years, like me):
You could create your own extension-method that also works with linq 2 sql. Example:
public static class LinqExtensions
{
public static IEnumerable<TResult> TakeIfNotNull<TResult>(this IEnumerable<TResult> source, int? count)
{
return !count.HasValue ? source : source.Take(count.Value);
}
}
this takes an int? instead of int and returns either the source-enumerable if count is null else it returns the result of default Take-method.
So you could write like:
.OrderByDescending(k => k.Count).TakeIfNotNull(numberOfRecords).ToList();
if numberOfCounts is null, it'll take all records.
As the right solution has already been posted by Tim, still I want your attention to the simpler solution, if suits to your requirement.
Add one more if condition at the top of this query.
if(allRecordRequired)
{
numberOfRecords = 2000000;
}
Leave your query as it is.
Pass a huge number to your method.A number that is equal (at least) or bigger than the items count.That should give you all records.

Returning Linq query results into a List object (based on condition)

I need to return a number of Linq query results into a List object based on a foreign key value. What is the syntax for doing this? I am new to using Linq, so below is my best guess so far. I receive an error in the .Where() "clause" stating "The name 'pt' does not exist in the current context. Any help would be greatly appreciated!
List<AgentProductTraining> productTraining = new List<AgentProductTraining>();
var prodCodes = productTraining.Select(pt => new[]
{
pt.ProductCode,
pt.NoteId,
pt.ControlId
})
.Where(pt.CourseCode == course.CourseCode);
You would need to switch the locations of where and select if you're using extension methods:
var prodCodes = productTraining.Where(pt => pt.CourseCode == course.CourseCode)
.Select(pt => new SomeRandomType
{
ProductCode = pt.ProductCode,
NoteId = pt.NoteId,
ControlId = pt.ControlId
});
I also recommend, as you can see above, that you create a type for that select statement so that you're not relying on anonymous types. You should put in into an object type that you know everything about.
Also, if CourseCode is a string, that should be pt.CourseCode.Equals(course.CourseCode).

LINQ to Entities does not recognize the method 'Boolean CheckMeetingSettings(Int64, Int64)' method

I am working with code first approach in EDM and facing an error for which I can't the solution.Pls help me
LINQ to Entities does not recognize the method 'Boolean
CheckMeetingSettings(Int64, Int64)' method, and this method cannot be
translated into a store expression.
My code is following(this is the query which I have written
from per in obj.tempPersonConferenceDbSet
where per.Conference.Id == 2
select new PersonDetials
{
Id = per.Person.Id,
JobTitle = per.Person.JobTitle,
CanSendMeetingRequest = CheckMeetingSettings(6327,per.Person.Id)
}
public bool CheckMeetingSettings(int,int)
{
///code I have written.
}
Please help me out of this.
EF can not convert custom code to SQL. Try iterating the result set and assigning the property outside the LINQ query.
var people = (from per in obj.tempPersonConferenceDbSet
where per.Conference.Id == 2
order by /**/
select new PersonDetials
{
Id = per.Person.Id,
JobTitle = per.Person.JobTitle,
}).Skip(/*records count to skip*/)
.Take(/*records count to retrieve*/)
.ToList();
people.ForEach(p => p.CanSendMeetingRequest = CheckMeetingSettings(6327, p.Id));
With Entity Framework, you cannot mix code that runs on the database server with code that runs inside the application. The only way you could write a query like this, is if you defined a function inside SQL Server to implement the code that you've written.
More information on how to expose that function to LINQ to Entities can be found here.
Alternatively, you would have to call CheckMeetingSettings outside the initial query, as Eranga demonstrated.
Try:
var personDetails = obj.tempPersonConferenceDbSet.Where(p=>p.ConferenceId == 2).AsEnumerable().Select(p=> new PersonDetials
{
Id = per.Person.Id,
JobTitle = per.Person.JobTitle,
CanSendMeetingRequest = CheckMeetingSettings(6327,per.Person.Id)
});
public bool CheckMeetingSettings(int,int)
{
///code I have written.
}
You must use AsEnumerable() so you can preform CheckMeetingSettings.
Linq to Entities can't translate your custom code into a SQL query.
You might consider first selecting only the database columns, then add a .ToList() to force the query to resolve. After you have those results you van do another select where you add the information from your CheckMeetingSettings method.
I'm more comfortable with the fluid syntax so I've used that in the following example.
var query = obj.tempPersonConferenceDbSet
.Where(per => per.Conference.Id == 2).Select(per => new { Id = per.Person.Id, JobTitle = per.Person.JobTitle })
.ToList()
.Select(per => new PersonDetails { Id = per.Id,
JobTitle = per.JobTitle,
CanSendMeetingRequest = CheckMeetingSettings(6327, per.Person.Id) })
If your CheckMeetingSettings method also accesses the database you might want to consider not using a seperate method to prevent a SELECT N+1 scenario and try to express the logic as part of the query in terms that the database can understand.

LINQ to Entities complex query

Is it possible ...??? I have 4 DropDownLists on my main page and the
user may select from any, all or some of
the DropDownLists. I am capturing their selection (or non-selection) using a SESSION
variable. What I would like to be able to do is pass the session
variable values to my Data Access Layer and build a WHERE clause
(maybe using StringBuilder) and then place that variable SOMEHOW into
my query expression. Is that possible??? Sorry, I'm a newbie. Thanks ~susan~
public class DLgetRestaurants
{
FVTCEntities db = new FVTCEntities();
public List<RESTAURANT> getRestaurants(string cuisineName, string priceName, string cityName)
[Build a string based on the values passed to the function]
{
var cuisineID = db.CUISINEs.First(s => s.CUISINE_NAME == cuisineName).CUISINE_ID;
List<RESTAURANT> result = (from RESTAURANT in db.RESTAURANTs.Include("CITY").Include("CUISINE").Include("Price")
where **[USE STRINGBUIDER EXPRSSION HERE]**
select RESTAURANT).ToList();
return result;
}
}
You can compose Where conditions which are linked by a logical AND relatively easy in LINQ extension method syntax:
var query = db.RESTAURANTs.Include("CITY").Include("CUISINE").Include("Price");
if (userHasSelectedInDDL1)
query = query.Where(r => r.PropertyForDDL1 == ValueFromDDL1);
if (userHasSelectedInDDL2)
query = query.Where(r => r.PropertyForDDL2 == ValueFromDDL2);
if (userHasSelectedInDDL3)
query = query.Where(r => r.PropertyForDDL3 == ValueFromDDL3);
if (userHasSelectedInDDL4)
query = query.Where(r => r.PropertyForDDL4 == ValueFromDDL4);
List<RESTAURANT> result = query.ToList();
For a much more flexible solution to build queries dynamically the Dynamic LINQ Library recommended by boca is probably the better choice.
I have done this in the past using the Dynamic Linq Library.

linq help - newbie

how come this work
public IQueryable<Category> getCategories(int postId)
{
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
var query = from c in categories.GetAll()
join pcm in postCategoryMap.GetAll() on c.CategoryId equals pcm.CategoryId
where pcm.PostId == 1
select new Category
{
Name = c.Name,
CategoryId = c.CategoryId
};
return query;
}
but this does not
public IQueryable<Category> getCategories(int postId)
{
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
var query = from c in categories.GetAll()
join pcm in postCategoryMap.GetAll() on c.CategoryId equals pcm.CategoryId
where pcm.PostId == postId
select new Category
{
Name = c.Name,
CategoryId = c.CategoryId
};
return query;
}
The issue is most likely in the implementation of the query provider.
pcm.PostId == 1
and
pcm.PostId == postId
actually have a big difference. In the expression tree the first is generated as a ConstantExpression which doesnt need to be evaulated.
With the second, the compiler actually generates an inner class here (this is the _DisplayClassX that you see). This class will have a property (will most likely be the same name as your parameter) and the expression tree will create a MemberAccessExpression which points to the auto-generated DisplayClassX. When you query provider comes accross this you need to Compile() the Lambda expression and evaluate the delegate to get the value to use in your query.
Hope this helps.
cosullivan
The problem is not the linq itself,
you need to be sure that the context or provider object is able to fetch the data.
try testing the
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
objects and see if they are populated or if they behaving as required.
you may want to search the generated code for c__DisplayClass1 and see what you can see there. some times the generated code dose some weird things.
when you step into you code check the locals and the variable values. this may also give you some clues.
Edit : Have you tried to return a List<> collection ? or an Enumerable type?
Edit : What is the real type of the item and query may not be iterable

Resources