Difference between First, FirstOrDefault and singleOrDefault keywords in ORM - linq

eI need to select a particular single data element from first row ordered descending by date. Please specify the differences between the following keywords.
First
FirstOrDefault
singleOrDefault
Also need the precedence/order and usage rules of placing Orderby, where & select in Linq ORM Query. It would be much helpful if answer could be clear & descriptive.
Thanks in advance

A quick Google gives you the following Questions which address your question:
When to use .First and when to use .FirstOrDefault with LINQ?
LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria
You might also find the following article useful as it goes into each method:
http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/
As stated in the answers, the names do give it away (to those familiar), but here's a quick overview:
First
Will return the first entry in a collection (one or more results returned), will throw an exception if no records returned.
FirstOrDefault
Will return the first entry in a collection (one or more results returned), will return the appropriate default object if no records returned
SingleOrDefault
This one isn't really the same as the previously mentioned functions, it will return the result only if only one record is returned, otherwise will return the appropriate default object.
I tend to use First if I know that my results will always return "something", I use FirstOrDefault when I just want the first element but know that sometimes the query might return nothing. I've yet to personally use SingleOrDefault but it should only be used where your query is only ever going to return one row and that returned results should be ignored if more than one result exists.

Related

Errors in the use of Specification<T>, returns one object out of 2 matching the search criteria

Errors in the use of Specification, returns one object out of 2 matching the search criteria, while builder returns the correct value.
springDatabaseItemRepository.findAll(builder.build(), pageable);
I'm looking for 3 conditions: 1 of which joins all queries and works. The other two are one simple query, the second is join connected using or. And after processing, only the results of join are returned to me.
I tried to change the processing and conditions, tried to read the documentation, but it didn't give me anything. Also, if you call join and a simple query separately, the results are returned correct.

Linq to Sharepoint results in invalid cast

I am programming a Silverlight application in c#, which takes lists from a sharepoint.
I want the distinct elements from a specific column in the list.
After getting the query I can't handle with the var-datatype. The program exists everytime, when I want to make a datacast, for example in an ListItemCollection.
Here is the code:
ListItemCollection bla;
var result = bla.Select(m => m["Region"]).Distinct();
ListItemCollection a = (ListItemCollection)result; //Error happens here
LINQ deals with instances of IEnumerable<> or IQueryable<>. Distinct returns an IEnumerable<> or IQueryable<> depending on the type of the original collection. In your case, it returns an IQueryable
You are trying to cast that IQueryable to a ListItemCollection, which understandably results in an invalid cast exception.
You don't need to do something else to start working with the items. You can iterate over them with foreach, convert them to an array or list with ToArray() and ToList() etc
Linq provider for SharePoint does not support Distinct operator which is why this error occurs.
According to MSDN:
Some LINQ queries cannot be completely translated into CAML. However,
however such queries can, in principle, run correctly because they can
be executed in two stages. First, the LINQ to SharePoint provider
translates as much of the query into CAML as it can and executes that
query
Please refer Unsupported LINQ Queries and Two-stage Queries for a more details.
Two stage approach
To correct this error, you should cut your queries in two stages to force the first query execution before the second one. To do that, you should for example transform the first IEnumerable<T> in a list thanks to ToList() method.
The following example demonstrates how to return unique values from ListItemCollection object:
var result = items.ToList().Select(i => i["Region"].ToString()).Distinct(); //System.Linq.Enumerable.DistinctIterator<string> type
foreach (var item in result)
{
//...
}

How to build a query across parent and child object fields in Oracle CRM On Demand?

As a part of an Integration Requirement, I need to query Opportunity records that have been Modified after a specific date and time?
Now, Opportunity has a child object called ProductRevenue with a one to many relationship. Is there anyway I can construct a querypage that will fetch records whose Opportunity fields 'OR' its child ProductRevenue's fields have been modified after a specific date and time?
I have tried using the SearchSpec argument, but it does not let me query across child object fields.
For eg:
ObjOpptyQueryPageInput.ListOfOpportunity.Opportunity.searchspec = "([ModifiedDate] > '01/01/2013 00:00:00') OR ([ProductRevenueData.ModifiedDate] >= '01/01/2013 00:00:00')";
[This above code written in C# thew me an error saying - The object Opportunity does not have an integration component called - ProductRevenueData.ModifiedDate.]
Any help will be greatly appreciated. Thank you.
I have been looking for the answer myself, and here is my understanding although not a solution.
In Web Services 2.0, Oracle says "all parent records matching the parent criteria and only children matching the child criteria are returned."
You actually can define "searchspec" on the parent AND the child, and it does work in the way that Oracle defined. However it is probably not the behavior you are looking for. When you do this what happens is you get ALL parents that match the parent.searchspec regardless of whether its child matches the child.searchspec. However those parents will only have the child(ren) that match your child.searchspec in the query result. So if all you wanted was "parents that have these children" or "these children" you are out of luck. Because what you get is "many parents and some of their children."
So even when you are post-processing with two queries you will have to spend some time. :(
By the way your two separate queries will have to look something like this:
query 1.
ObjOpptyQueryPageInput.ListOfOpportunity.Opportunity.searchspec = "([ModifiedDate] > '01/01/2013 00:00:00')";
query 2. ObjOpptyQueryPageInput.ListOfOpportunity.Opportunity.ListOfProductRevenue.ProductRevenue.searchspec = "([ModifiedDate] >= '01/01/2013 00:00:00')";
Then post-process query 2 to take out all parents who have no children.
Then union that with the results from query 1.
From my experience, you will not be able to do this using their V2.0 api (i.e. searchspec). You can perform this using V1.0 api BUT this will return all parent records matching your criteria plus all related ProductRevenue records whether they meet the criteria or not. I do something similar and then post process the data against an xpath predicate filter. The only other option, I think, is 2 separate queries.
I had the same problem, and i tried many ways to resolve the problem, but for now you should deal with the result returned: you can use DOM, XPath or regular expressions to extract the information you want for the returned result.
In my case i used XPath because it's very fast and more easier. This is a link to the question i have posted with the correct answer :
Xpath solution for the parent-child query result
I hope this will fix the problem.

LINQ Lambda Order in writing the query

I have the following query:
var query = db.Prog
.Where (a => a.Prog != "00000" && a.fn != "Koll")
.Select(a => new {a.Prog, a.MEfn})
.OrderByDescending(a => a.MEfn)
The query works fine but wondering if there are general rules on the order in which you write a Lambda linq query. Meaning, .Where comes before .Select, etc.
Can somebody enlighten me on the order in which LINQ needs to be written or best practices.
There isn't a best practice on the order in which you write a LINQ query, it will depend on if you want to do your filtering first, or your projection. For example in your case, you are projecting to an anonymous type which doesn't include the 'fn' property which your filter uses, so it wouldn't be available to use in a where clause if your select was first.
A better practice would be to give your properties less cryptic names. Also, 'fn' doesn't follow the PascalCase for property names, and if it's a field then it probably shouldn't be public.
Yours can be a good order.
Let's distinguish the case where db points to an SQL DB with a very good LINQ provider and the case db is an in-memory object. I guess it's the first.
In case you are using a LINQ to SQL provider, the statements are evaluated only when you materialize the query into an object, so the SQL optimizer (inside the DB) will take care of ordering of statements.
The vice versa occurs when your statements are run against in-memory collections or to materialized collections coming from LINQ to SQL. In that case they are executed sequentially, so you want to execute first those statements that reduce the number of results in the collection. Where is the best candidate!!!
The order that they should be in are completely dependent on the context of what you are doing. So if your OrderBy is simply formatting the data to be friendly to view, put it at the end after you have trimmed your collection, if your looking for the First value of a sorted collection then maybe you would need it before the collection is iterated to get the first.

This filters in memory right?

I Just want to make sure I understand this correctly...
search is an object that contains a querystring.
Repo.Query returns an ObjectQuery<T>.
From my understanding the chained linq statements will filter the results after entity framework has returned all the rows satisfying the query. So really ALL the rows are being returned and THEN filtered in memory. So we are returning a bunch of data that we don't really want. There's about 10k rows being returned so this is kind of important. Just like to get my confusion cleared up.
var searchQuery = Repo.Query(search)
.Where(entity =>
entity.Prop1.ToUpper().Equals(prop1.ToUpper()) &&
entity.Prop2.ToUpper().Equals(prop2.ToUpper()))
.OrderBy(entity => Repo.SortExpression ?? entity.prop1);
Your Repo.Query(string query) function should return IQueryable<T>.
Then you can filter and order without getting all rows first.
IQueryable(Of T) Interface
hope this helps
If this is to SQL, this will most likely create a SQL query and filter on the server and not in memory.
As a matter of fact, the statement above wouldn't actually do anything.
It's only when you iterate over it that the query will be executed. This is why certain providers (like the EF to SQL one) can collapse expression trees into a SQL query.
Easiest way to check is to use LINQPAD or the SQL Profiler to see what query is actually is executed.

Resources