Basic LINQ query to SQL C# - c#

I have this LINQ query in C# for querying a db4o database.
IEnumerable<internetRecord> searchResult = from internetRecord ie in database
where ie.GSrecordID.Contains(txtSearchString.Text)
select ie;
What would be the equivalent query in SQL? (needed for comparison purposes) I have not worked with SQL much in the past and looking at it after using LINQ for a while it seems confusing.

SELECT *
FROM MyTable
WHERE GSRecordID LIKE '%txtSearchString%'

Select * from internetrecord where GSrecordID like '%your comparison string%'
Provided internetrecord is your SQL table GSrecordID is the column of your table.

I don't know much about db40 but in standard SQL it would be:
SELECT * FROM internetRecord
WHERE GSrecordID LIKE '%txtSearchString%'

YOu can do something like this
var result = database.Where(x => x.GSrecordID.Contains(txtSearchString.Text));

Related

LINQ to SQL will not generate sargable query

I'm using LINQ To Sql (not Entity Framework), the System.Data.Linq.DataContext library, hitting a SQL Server 2005 database and using .Net Framework 4.
The table dbo.Dogs has a column "Active" of type CHAR(1) NULL. If I was writing straight SQL the query would be:
SELECT * FROM dbo.Dogs where Active = 'A';
The LINQ query is this:
from d in myDataContext.Dogs where d.Active == 'A' select d;
The SQL that gets generated from the above LINQ query converts the Active field to UNICODE. This means I cannot use the index on the dbo.Dogs.Active column, slowing the query significantly:
SELECT [t0].Name, [t0].Active
FROM [dbo].[Dog] AS [t0]
WHERE UNICODE([t0].[Active]) = #p1
Is there anything I can do to stop Linq to Sql from inserting that UNICODE() call (and thus losing the benefit of my index on dogs.Active)? I tried wrapping the parameters using the EntityFunctions.AsNonUnicode() method, but that did no good (it inserted a CONVERT() to NVARCHAR instead of UNICODE() in the generated sql), eg:
...where d.Active.ToString() == EntityFunctions.AsNonUnicode('A'.ToString());
Linq is meant to make it easier to write queries and does not always generate optimal SQL. Sometimes when high performance is required it is more efficient to write raw SQL directly against the database, the Linq datacontext supports mapping of SQL result to entities just like linq.
In your case I would suggest writing:
IEnumerable<Dog> results = db.ExecuteQuery<Dog>(
"SELECT * FROM dbo.Dogs where Active = {0}",
'A');
This is an old question, but I bumped into this recently.
Instead of writing
from d in myDataContext.Dogs where d.Active == 'A' select d;
Write
from d in myDataContext.Dogs where d.Active.Equals('A') select d;
This will produce the desired SQL without having to resort to any of the "hacks" mentioned in other answers. I can't say why for certain.
I've posted that as a question, so we'll see if we get any good answers.
There's not much you can do to the way LINQ queries are translated into SQL statements, but you can write a stored procedure that contains your queries and call that SP as a LINQ2SQL function. This way you should get full benefit of SQL Server optimizaions
You can do a little hack (as it is often required with LINQ to SQL and EF). Declare the property as NCHAR in the dbml. I hope that will remove the need to do the UNICODE conversion. We are tricking L2S in a benign way with that.
Maybe you need to also insert the EntityFunctions.AsNonUnicode call to make the right hand side a non-unicode type.
You can also try mapping the column as varchar.

Using query expressions for Unicode strings with LINQ

I am working with LINQ and and I have a database with columns for storing local content(non-english characters). Now I want to make a query using linq as follows
var desc = from p in db.GetDesc
where p.Category.Contains("xxxx".ToString())
orderby p.Date descending
select p;
Here the Category column contains unicode strings and the above query string doesn't work. How can I use natural language queries with LINQ?
Unicode in general should work fine with Linq to SQL and Linq to Entities against SQL Server (which I assume you're using). In fact your query should be
var desc = from p in db.GetDesc
where p.Category.Contains("xxxx")
orderby p.Date descending
select p;
There's no need to use .ToString(), since "xxxx" is already a Unicode string.
The problem seems to be with SQL Server. I tried your query against a table containing your Ethiopian characters, and as you say it doesn't work. If I query for .Contains("ስፖርት") then all rows are returned.
Running the SQL directly has the same result.
Trying a simple query like this fails (returns all rows)
select * from TestTable where Title like N'%' + NCHAR(0x1275) + N'%'
Here 0x1275 is the Unicode code point of the ት character.
If we look at the SQL documentation for NCHAR we see that only Unicode code points upto 4000 are supported. Unfortunately 0x1275 = 4725 so it looks like SQL Server (even 2012) won't support Ethiopian characters.
Having read that 4000 is the limit, testing reveals that running the above simple query with NCHAR(3129) succeeds (in my case returns no rows), but >= 3130 fails (returns all rows).

Convert SQL query in LINQ query and move results into new datatable

I have a DataTable, and need to extract the data by using this SQL query:
SELECT code_direction, count(TP) AS CN FROM table1 WHERE
cod_time = 'A011' GROUP BY TP,code_direction;
Which is the C# LINQ equivalent query?
After it I want to move the results into a new DataTable.
I tried many examples founded around in web but no this specific logic.
Linqer is your friend!
This tool can translate SQL to LINQ. You can download it at http://www.sqltolinq.com.
Note that it's not always possible to convert a SQL query straight into a 100% equivalent LINQ query, but it should be close enough.
If you need translation in the other direction -- from LINQ to SQL -- you can use LINQPad. Download it at http://www.linqpad.net/.

Union with NHibernate and Criteria?

Union with NHibernate and Criteria:
Is it possible in Criteria or QueryOver?
If not, is there any other way to achieve a union of two result within the same query?
You can't do a union directly, but you can do two future queries and union the results in code:
var resultSet1 = this.Session.CreateCriteria<A>().Future<A>();
var resultSet2 = this.Session.CreateCriteria<B>().Future<B>();
After this, when either result set is enumerated, NHibernate will issue a single query to the database which will return multiple result sets. Note, if you are not using SQL Server, the database may not support multiple result sets.
This is not possible even using HQL. See this other S.O. post
One way is to drop back to raw SQL and use a named query
<sql-query name="MyQuery">
<![CDATA[
select col1,col2 from table1
union
select col1,colA from table2
]]>
</sql-query>
And use the AliasToBeanResultTransformer to transform it back into your DTO/POCO
var query = Session
.GetNamedQuery("MyQuery")
.SetResultTransformer(new AliasToBeanResultTransformer(typeof(MyDto)));
return query.List<MyDto>();
You can use -
NHibernate.Criterion.Restrictions.Or(ICriterion FirstQuery,
ICriterion SecondQuery)
as your Criteria in a single query.

Why linq fail to get temp table values

work on C# vs2008. I have a stored procedure ,This procedure holds temp table ,i need to get the temp table values.My sql query is bellow:
create procedure [dbo].[TestProcedure]
as
SELECT * INTO #temp1 from(select * from DischargePort) as b
select * from #temp1
drop table #temp1
My above query has a temp table named #temp1.After run this query in sql-server-management i get result ,but when i try to execute this procedure in linq ,I get no result.My linq syntax is bellow:
var r = ProviderName.TestProcedure();
Can anybody tell me why this problem arise,How to overcome this problem.Hope any body not say that linq can not handled the temp table or this kind of word.if have any query plz ask .Thanks in advance.
I don't think this is anything to do with the temporary table, but rather that Linq does not know what output is to expected.
With Dotnet Framework 4, this is easy, as you can do something like
(from r in ProviderName.TestProcedure().AsDynamic()
select new { r.Id, r.Description}).ToList()
(assumes Id and description are fields in DischargePort)
Otherwise, you need to do something in your designer to tell Linq what your procedure outputs. I have never had to do this, but perhaps this article will help.
When I think about it, in this particular case, you should be able to do something like
var results = (from r in ExecuteQuery<DischargePort>("exec TestProcedure")
select r ).ToList();
i would start by downloading linqpad to see the sql that linq is emitting, this may provide some clues. you could also use the sql profiler tool to see what query is being run.

Categories

Resources