LINQ Count() but don't return all rows - linq

I need to get a count of a DB table.
When I do the below I can see that the table enumerates (so looks like the rows come back then get counted on the app server side) but I'd like the SQL server to do the counting then return just the count.
db.Places.Where(x => x.City == 'San Jose').Count()

This totally depends on the Linq to SQL provider that you're using, but most of them should translate your LINQ statement into an actual server side count.
You will need to enable logging on your provider or turn on profiling on your database in order to see what actual SQL was sent to it.
PS: Please tag with the appropriate provider and SQL server (for example: linq-to-sql sql-server)

Related

Oracle Rest – filtering by columns (vertical filtering)

I would like to specify in Oracle REST query which columns should be returned in the select statement.
One of the solution would be to use view, however in my case I would like to select columns in a dynamic fashion.
Such functionality is available in PostgREST: http://postgrest.org/en/v6.0/api.html#vertical-filtering-columns
Is there such feature in Oracle REST Data Services?
No, we offer row filtering but not column selection.
So i can say which rows I want to come back via the URI, but I cannot say which columns I want.
So if you REST enable a table or view, it will be all of those columns, of it it's a RESTful Service, it will be the columns you have included in your SELECT.
Something else to keep in mind, we do have a REST Enabled SQL Feature...where you POST your query, and we get you the results. So in the POST you could specify the columns you want.

How to make Oracle 'order by' behave like SQLServer?

i'm trying to write an Oracle query that sorts the results in the same way as MS SQL Server does. I'm toying with the 'NLSSORT' function and it's parameters but i can't get exactly the same results as what i can see with MS SQL Server.
The context is a generic data collection system that supports both Oracle and MS SQL Server. This is a pretty old system that is still under maintenance and development. No entity framework or any recent approaches to handle database interactions.
With a simple order by on MS SQL Server i get this result:
_TEST
04-00031-IPE
04-00044-OG
0A-A
A0-A
SAZ2217
The same query on Oracle returns this:
04-00031-IPE
04-00044-OG
0A-A
A0-A
SAZ2217
_TEST
I have tried many combinations of NLSSORT parameters without any success.
[edit]
By using the 'PUNCTUATION' NLS_SORT parameter value, i get results very close to the MS SQL sorting but there is still differences with substrings that contains sequences of numeric chars. Here is a sample query result:
Oracle
0031-CASTOR-BLOC1-AV-AP
0031-CASTOR-BLOC1-AV-SP
0031-CASTOR-BLOC1-SV-AP
0031-CASTOR-BLOC1-SV-SP
0031-CASTOR-BLOC10-DV-AP
0031-CASTOR-BLOC10-DV-SP
0031-CASTOR-BLOC2-DV-AP
Ms SQL
0031-CASTOR-BLOC10-DV-AP
0031-CASTOR-BLOC10-DV-SP
0031-CASTOR-BLOC1-AV-AP
0031-CASTOR-BLOC1-AV-SP
0031-CASTOR-BLOC1-SV-AP
0031-CASTOR-BLOC1-SV-SP
0031-CASTOR-BLOC2-DV-AP
Thank you for your help!
I finally found this solution:
ORDER BY NLSSORT(COLUMN_NAME, 'NLS_SORT = FRENCH_M')
At least in my particular context, i get the same sorting under both MS SQL Server (default sorting) and Oracle.
Here is two useful links:
http://www.myoracleguide.com/xl/Linguistic_Sorting_Frequently_Asked_Questions.htm
http://download.oracle.com/docs/cd/B19306_01/server.102/b14225/ch5lingsort.htm#NLSPG005
Could consider use of rpad function?
e.g.
select name, rpad(upper(replace(translate(name,'_','+'),'-','') ),15,'0') as v1
from sorttest order by
rpad(upper(replace(translate(name,'_','+'),'-','') ),15,'0')

LINQ and Generated sql

suppose my LINQ query is like
var qry = from c in nwEntitiesContext.CategorySet.AsEnumerable()
let products = this.GetProducts().WithCategoryID(c.CategoryID)
select new Model.Category
{
ID = c.CategoryID,
Name = c.CategoryName,
Products = new Model.LazyList<Core.Model.Product>(products)
};
return qry.AsQueryable();
i just want to know what query it will generate at runtime....how to see what query it is generating from VS2010 IDE when we run the code in debug mode....guide me step by step.
There is not much to see here - it will just select all fields from the Category table since you call AsEnumerable thus fetching all the data from the Category table into memory. After that you are in object space. Well, depending on what this.GetProducts() does - and my guess it makes another EF query fetching the results into memory. If that's the case, I would strongly recommend you to post another question with this code and the code of your GetProducts method so that we can take a look and rewrite this in a more optimal way. (Apart from this, you are projecting onto a mapped entity Model.Category which again won't (and should not) work with Linq-to-Entities.)
Before reading into your query I was going to recommend doing something like this:
string sqlQueryString = ((ObjectQuery)qry).ToTraceString();
But that won't work since you are mixing Linq-to-Entities with Linq-to-objects and you will actually have several queries executed in case GetProducts queries EF. You can separate the part with your EF query and see the SQL like this though:
string sqlString = nwEntitiesContext.CategorySet.ToTraceString();
but as I mentioned earlier - that would just select everything from the Categories table.
In your case (unless you rewrite your code in a drastic way), you actually want to see what queries are run against the DB when you execute the code and enumerate the results of the queries. See this question:
exact sql query executed by Entity Framework
Your choices are SQL Server Profiler and Entity Framework Profiler. You can also try out LinqPad, but in general I still recommend you to describe what your queries are doing in more detail (and most probably rewrite them in a more optimal way before proceeding).
Try Linqpad
This will produce SELECT * FROM Categories. Nothing more. Once you call AsEnumerable you are in Linq-to-objects and there is no way to get back to Linq-to-entities (AsQueryable doesn't do that).
If you want to see what query is generated use SQL Profiler or any method described in this article.

How to optimize the running of Oracle orderby native query running in EJB (Oc4j)?

I've the following problem with EJB and Oracle database.
I've some native SQL query deployed in Oc4j that returns more than 21k rows from Oracle DB. when I run the query against Oracle DB I get JOOM (out of memory) exception.
And because the requirements was to include pagination for the result set, so we decided to use em.setMaxResult, em.setFirstResult to return only 10 rows a time.
Using the EntityManager to implement the pagination put us in some problem As Later, it was required to sort the result returned, but the whole result not just the 10 rows returned by setMaxResult()! We found that, to put the clause ORDER BY xxxx in the native query makes the query performance became too bad.
So, we are considering doing the pagination in the Database layer (using Oracle rownum or any other technique).
Later, we recognized that, If we use em.clear() we might be able to avoid the JOOM exception by making something like:
define the result list
while database has more records
{
use entityManager get next 10 records and add them to the result list
entityManager.clear();
}
return result list
So, we could implement the paging on the Servlet side (using session.getAttribute("all_result").sublist(from, to)) and thus we can do the sort using Java as opposite to SQL sort.
Provided code for pagination, might help you.
em.createQuery("Select o from Entity o where o.id > :lastId order by o.id");
query.setParameter("lastId", previousResult.get(previousResult.size()-1).getId());
query.setMaxResults(10);

Using XQuery in Linq To SQL?

Let's say I have a table that has a column of XML type data. Within SQL, I can execute the following statement:
select top 10 *,
Content.value('(/root/item/value)[1]', 'float') as Value
from xmltabletest
where Content.value('(/root/item/MessageType)[1]', 'int') = 1
The result set contains only the records matching the criteria, and it extracts a value from the XML into a column called 'Value'. Nice and simple.
Can the same thing be achieved with Linq To SQL?
I'd like to get SQL to do the heavy lifting and only return data matching my criteria rather than having to select, transfer, and then process a potentially massive chunk of data. As far as I can tell this isn't possible at the moment, but I thought I should ask.
(The environment is .NET 3.5, VS2008, SQL Server 2005 if that helps)
I'm not exactly sure if this is out of date now, but according to Scott Guthrie XML datatypes are:
represented as strings in LINQ to SQL
Entities. You could use XLINQ to query
on an XML column within your LINQ to
SQL entitiy - but this querying would
happen in your middle-tier (within
ASP.NET). You can't execute a remote
XQuery against the database and filter
returned results based on that in the
first release.
So in answer to your question, I'd say "no."

Resources