WebApi reordering results? - asp.net-web-api

I hav a problem with WebApi and OData. Slowly moving an API over and... now it seems that the framework is reordering the results.
The following code:
[EnableQuery(PageSize = 100, MaxTop = 1000, AllowedQueryOptions = AllowedQueryOptions.All)]
[ODataRoute]
public IEnumerable<Reflexo.Api.GrdJob> Get(ODataQueryOptions options) {
var nodes = Repository.GrdJob
.Include(x=>x.Cluster)
.OrderByDescending(x => x.Id)
.Select(x => new Reflexo.Api.GrdJob() {
Id = x.Id,
Identity = x.Code,
}).AsQueryable();
nodes = (IQueryable<Reflexo.Api.GrdJob>)options.ApplyTo(nodes);
var retval = nodes.ToArray();
return nodes;
}
is as simlple as it gets. Comparing the results in the debugger with what I can see on the screen calling the method... the results have a different order.
Note that I am comparing the db side id fields (id) of both the JSON I see in a browser and the fields in the array named retval. I have imposed an artificial default order - which also get into the SQL (checked) and array (checked).
Just the JSON shows results in a different order.
Am I missing something?

Be aware the EnableQueryAttribute is going to execute ODataQueryOptions.ApplyTo again using a default set of query settings. (See the EnableQueryAttribute.ApplyQuery method source.) Try removing the attribute.

Thanks to the other contributors on this post. I ran into the same issue described above, and managed to disable OData's default sorting by adding the EnsureStableOrdering = false to my [EnableQuery()] attribute.

Related

Umbraco 7 - Query Umbraco Members - Performance

I made this function to fetch all the members with their custom properties. I was just wondering whether this is written performant or not. Are there any - performance wise - cleaner solutions? Or is it okay to work with?
public List<DashboardMemberModel> GetAllMembers()
{
//Members
var members = ApplicationContext.Services.MemberService.GetAllMembers();
//Populate List<DashboardMemberModel> & Return
return members.Select(member => new DashboardMemberModel
{
Id = member.Id,
FirstName = Umbraco.TypedMember(member.Id).GetPropertyValue("firstName").ToString(),
LastName = Umbraco.TypedMember(member.Id).GetPropertyValue("lastName").ToString(),
Company = Umbraco.TypedMember(member.Id).GetPropertyValue("companyName").ToString()
}).OrderBy(member => member.Id).ToList();
}
Kind regards
You could use the Lucene index instead - this is what the MemberListView does. Read the code on GitHub here:
https://github.com/robertjf/umbMemberListView/blob/master/MemberListView/Helpers/MemberSearch.cs
You may also want to add additional attributes to the Member Index.

executeQueryLocally does not work well when using withParameters

I'm trying to use executeQueryLocally in a query that has 'withParamters', but it seems that I get locally cached data even when using new values in the 'withParameters'. It is as if 'executeQueryLocally' ignores values in 'withParameters'.
here is the code in the client side:
var query = EntityQuery.from('ProductsFilteredByCategory')
.withParameters({ categoryId: categoryId })
.select("productId,name,desc,shopPrice,webPrice")
.orderBy('name');
var p = manager.executeQueryLocally(query);
if (p.length > 5) {
productsObservable(p);
return Q.resolve();
}
here is the code for 'ProductsFilteredByCategory' on the server side:
[HttpGet]
public IQueryable<Product> ProductsFilteredByCategory(int categoryId)
{
Category category = _contextProvider.Context.Categories.Include("Products").Include("SubCategories").First(c => c.CategoryId == categoryId);
var prods = from p in category.Products select p;
category.SubCategories.ForEach(sc => prods = prods.Concat(_contextProvider.Context.Categories.Include("Products").First(c => c.CategoryId == sc.CategoryId).Products));
return prods.AsQueryable();
}
what happens is that after I retrieve the data once with 'p.length > 5' being true, in every subsequent call 'p.length > 5' is still true even when 'categoryId' is different, so the data that is bound to the observable is loaded once and never changes.
Thanks for your help !
Elior
The EntityQuery.withParameters method is NOT intended for local query use. (We should probably document this better).
WithParameters sends application domain specific parameters that can only be interpreted on the server. Unlike with 'where', 'orderBy', 'take' etc, there is no global interpretation that can be determined for a withParameters call. It can only be understood within the context of the server side method that accepts the parameters.

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.

Entity Framework 4 - List<T> Order By based on T's children's property

I have the following code -
public void LoadAllContacts()
{
var db = new ContextDB();
var contacts = db.LocalContacts.ToList();
grdItems.DataSource = contacts.OrderBy(x => x.Areas.OrderBy(y => y.Name));
grdItems.DataBind();
}
I'm trying to sort the list of the contacts according to the area name that is contained within each contact. When I tried the above, I get "At least one object must implement IComparable.". Is there an easy way instead of writing a custom IComparer?
Thanks!
try this:
public void LoadAllContacts()
{
var db = new ContextDB();
var contacts = db.LocalContacts.ToList();
grdItems.DataSource = contacts.OrderBy(x => x.Areas.OrderBy(y => y.Name).First().Name);
grdItems.DataBind();
}
this will order the contacts by the first area name, after ordering the areas by name.
Hope this helps :)
Edit: fixed error in code. (.First().Name)
I was in a discussion with #AbdouMoumen but in the end I thought I'd provide my own answer :-)
His answer works, but there two performance issues in this code (both in the answer as in the original question).
First, the code loads ALL contacts in the db. This may or may not be a problem, but in general I would recommend NOT to do this. Many modern controls support paging/filtering out of the box, so you'd be better off supplying an not-yet-evaluated IQueryable<T> instead of List<T>. If however you need everything in memory, you should delay the ToList to the last possible moment.
Second, in AbdouMoumen's answer, there is a so-called 'SELECT N+1' problem. Entity Framework will by default use lazy loading to fetch additional properties. I.e. the Areas property will not be fetched from the database until it's accessed. In this case this will happen in the controls 'for loop', while it's ordering the result set by name.
Open up SQL Server Profiler to see what I mean: you will see a SELECT statement for all the contacts, and an additional SELECT statement for each contact that fetches the Areas for that contact.
A much better solution would be the following:
public void LoadAllContacts()
{
using (var db = new ContextDB())
{
// note: no ToList() yet, just defining the query
var contactsQuery = db.LocalContacts
.OrderBy(x => x.Areas
.OrderBy(y => y.Name)
.First().Name);
// fetch all the contacts, correctly ordered in the DB
grdItems.DataSource = contactsQuery.ToList();
grdItems.DataBind();
}
}
Is it one to one relation (Contact->Area)?
if yeah then try the following :
public partial class Contact
{
public string AreaName
{
get
{
if (this.Area != null)
return this.Area.Name;
return string.Empty;
}
}
}
then
grdItems.DataSource = contacts.OrderBy(x => x.AreaName);

Resources