how can I see the inputs to a LINQ query? - linq

I've got a LINQ query that looks like this (at the end):
var query = from myTable0 ...
where myTable1.attributeId == 123 && (bunchaStrings.Contains(myTable1.attributeName)) && myTable2.yesNoValue == 'Y'
When I see the query it turns into this
SELECT ... FROM ... INNER JOIN ... WHERE ... AND (UNICODE([t3].[yesNoValue]) = #p3
So what's happening here is that the value of 'Y' is getting turned into '89' via the UNICODE function. That's all fine, but I'd really like to just be able to see the value of #p3 directly and I can't figure out how to see that value via any methods available from my var.

I would recommend piping the generated SQL out to the output window. There you will be able to see the whole SQL and your parameters values. Then it can also be logged.
Code for it can be found here ->
http://www.u2u.info/Blogs/Kris/Lists/Posts/Post.aspx?ID=11
Or an easier method (if you've got a handy console around):
MyDataContext context = new MyDataContext()
context.Log = Console.Out

You may also be interested in the LINQ to SQL Visualizer : http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx

Related

ActiveRecord 4 cannot retrieve "select AS" field

Ok, I feel really stupid for asking this, but it's driving me nuts and I can't figure it out. The docs say I should be able to use select AS in a Rails/ActiveRecord query. So:
d = Dvd.where(id: 1).select("title AS my_title")
Is a valid query and if I do a to_sql on it, it produces the expected SQL:
SELECT title AS my_title FROM `dvd` WHERE `dvd`.`id` = 1
However, d.my_title will give an error:
NoMethodError: undefined method `my_title' for #<ActiveRecord::Relation
I need to be able to use AS since the columns I want to retrieve from different joins have the same name so I can't access them the "regular" way and have to resort to using AS.
I also don't want to resort to using find_by_sql for future compatibility and a possible switch form Mysql to PostGresql.
Just to clarify, what I'm really trying to do is write this SQL in a Railsy way:
SELECT tracks.name AS track_name, artists.name AS artist_name, composers.name AS composer_name, duration
FROM `tracks_cds`
INNER JOIN `tracks` ON `tracks`.`id` = `tracks_cds`.`track_id`
INNER JOIN `artists` ON `artists`.`id` = `tracks_cds`.`artist_id`
INNER JOIN `composers` ON `composers`.`id` = `tracks_cds`.`composer_id`
WHERE cd_id = cd.id
The top example was just a simplification of the fact that SELECT AS will not give you an easy way to refer to custom fields which I find hard to believe.
ActiveRecord automatically creates getter and setter methods for attributes based on the column names in the database, so there will be none defined for my_title.
Regarding the same common names, why not just do this:
d = Dvd.where(id: 1).select("dvds.title")
You can write your sql query and then just pass into ActiveRecord's execute method
query = "SELECT title AS my_title FROM `dvd` WHERE `dvd`.`id` = 1"
result = ActiveRecord::Base.connection.execute(query)

EntityFramework Linq query

I cannot understand what is wrong with following query:
var tmp = dbset.AsEnumerable<mytable>().Where(
c=>c.Barcode.Contains("11") && c.Description.Contains("EW") );
return tmp;
Should this be same as:
select * from mytable
where Barcode like '%11%' and Description like '%EW%';
If I run this in sql server i get four rows as it should be, but not when I run the linq query
i get 0 rows.
Can please someone help me. It is rather a simple query and it is giving me such a headache. Thank you very much
You forget fetch data, do this:
var tmp = dbset.AsEnumerable<mytable>().Where(
c=>c.Barcode.Contains("11") && c.Description.Contains("EW") );
return tmp.ToList();
Also do not call AsEnumerable soon, use it as below:
var tmp = ctx.mytable.Where(
c=>c.Barcode.Contains("11") && c.Description.Contains("EW") );
return tmp.ToList();
dbset.AsEnumerable<mytable>()...
Don't do that!
You are causing all your data to get pulled from the database before checking the Where condition.
Other than that, it's not really clear why your query isn't working. Your syntax is correct. I'm guessing the data doesn't actually look like you think it does. Either that, or you're expecting like %EW% to match something in a case-insensitive manner and since the Where clause is being evaluated by LINQ to Objects you're not getting that behavior.
Run a query with only one condition? " c.Barcode.Contains("11") ".
That code should run fine.

LINQ 2 Entities-query is not working, but why?

everyone! ))
Here is code.
var existingEntities = (from record in globalOne.serviceContext.records_out
where record.timestamp.Date == DateTime.Now.Date
select record ).ToList();
It doesn't work.
Another code:
var existingEntities = (from record in globalOne.serviceContext.records_out
where record.timestamp.Day == DateTime.Now.Day
select record ).ToList();
It does work.
So, problem id in next string:
where record.timestamp.**Date** == DateTime.Now.Date
also won't do
where record.timestamp.Date.Equals(DateTime.Now.Date)
But why? I have no clue. "Timestamp" field is dateTime field in MS SQL SERVER.
And - there is NO records in table.
And I almost forgot - what does it mean - "doesn't work".
App just will not reach the breakpoint after that query(first), without any error, without anything.
Thanks.
You can call record.timestamp.Date because EF can't convert it to required expression tree (then convert it to sql command). In fact EF supports limited number of functions and properties, But for DateTime, EF has some good Canonical functions. You can use them in your case, e.g you can use Day(),Month(),Year() functions to solve your problem (see the link).

NHibernate IQueryable doesn't seem to delay execution

I'm using NHibernate 3.2 and I have a repository method that looks like:
public IEnumerable<MyModel> GetActiveMyModel()
{
return from m in Session.Query<MyModel>()
where m.Active == true
select m;
}
Which works as expected. However, sometimes when I use this method I want to filter it further:
var models = MyRepository.GetActiveMyModel();
var filtered = from m in models
where m.ID < 100
select new { m.Name };
Which produces the same SQL as the first one and the second filter and select must be done after the fact. I thought the whole point in LINQ is that it formed an expression tree that was unravelled when it's needed and therefore the correct SQL for the job could be created, saving my database requests.
If not, it means all of my repository methods have to return exactly what is needed and I can't make use of LINQ further down the chain without taking a penalty.
Have I got this wrong?
Updated
In response to the comment below: I omitted the line where I iterate over the results, which causes the initial SQL to be run (WHERE Active = 1) and the second filter (ID < 100) is obviously done in .NET.
Also, If I replace the second chunk of code with
var models = MyRepository.GetActiveMyModel();
var filtered = from m in models
where m.Items.Count > 0
select new { m.Name };
It generates the initial SQL to retrieve the active records and then runs a separate SQL statement for each record to find out how many Items it has, rather than writing something like I'd expect:
SELECT Name
FROM MyModel m
WHERE Active = 1
AND (SELECT COUNT(*) FROM Items WHERE MyModelID = m.ID) > 0
You are returning IEnumerable<MyModel> from the method, which will cause in-memory evaluation from that point on, even if the underlying sequence is IQueryable<MyModel>.
If you want to allow code after GetActiveMyModel to add to the SQL query, return IQueryable<MyModel> instead.
You're running IEnumerable's extension method "Where" instead of IQueryable's. It will still evaluate lazily and give the same output, however it evaluates the IQueryable on entry and you're filtering the collection in memory instead of against the database.
When you later add an extra condition on another table (the count), it has to lazily fetch each and every one of the Items collections from the database since it has already evaluated the IQueryable before it knew about the condition.
(Yes, I would also like to be the extensive extension methods on IEnumerable to instead be virtual members, but, alas, they're not)

LINQ syntax where string value is not null or empty

I'm trying to do a query like so...
query.Where(x => !string.IsNullOrEmpty(x.PropertyName));
but it fails...
so for now I have implemented the following, which works...
query.Where(x => (x.PropertyName ?? string.Empty) != string.Empty);
is there a better (more native?) way that LINQ handles this?
EDIT
apologize! didn't include the provider... This is using LINQ to SQL
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367077
Problem Statement
It's possible to write LINQ to SQL that gets all rows that have either null or an empty string in a given field, but it's not possible to use string.IsNullOrEmpty to do it, even though many other string methods map to LINQ to SQL.
Proposed Solution
Allow string.IsNullOrEmpty in a LINQ to SQL where clause so that these two queries have the same result:
var fieldNullOrEmpty =
from item in db.SomeTable
where item.SomeField == null || item.SomeField.Equals(string.Empty)
select item;
var fieldNullOrEmpty2 =
from item in db.SomeTable
where string.IsNullOrEmpty(item.SomeField)
select item;
Other Reading:
1. DevArt
2. Dervalp.com
3. StackOverflow Post
This won't fail on Linq2Objects, but it will fail for Linq2SQL, so I am assuming that you are talking about the SQL provider or something similar.
The reason has to do with the way that the SQL provider handles your lambda expression. It doesn't take it as a function Func<P,T>, but an expression Expression<Func<P,T>>. It takes that expression tree and translates it so an actual SQL statement, which it sends off to the server.
The translator knows how to handle basic operators, but it doesn't know how to handle methods on objects. It doesn't know that IsNullOrEmpty(x) translates to return x == null || x == string.empty. That has to be done explicitly for the translation to SQL to take place.
This will work fine with Linq to Objects. However, some LINQ providers have difficulty running CLR methods as part of the query. This is expecially true of some database providers.
The problem is that the DB providers try to move and compile the LINQ query as a database query, to prevent pulling all of the objects across the wire. This is a good thing, but does occasionally restrict the flexibility in your predicates.
Unfortunately, without checking the provider documentation, it's difficult to always know exactly what will or will not be supported directly in the provider. It looks like your provider allows comparisons, but not the string check. I'd guess that, in your case, this is probably about as good of an approach as you can get. (It's really not that different from the IsNullOrEmpty check, other than creating the "string.Empty" instance for comparison, but that's minor.)
... 12 years ago :) But still, some one may found it helpful:
Often it is good to check white spaces too
query.Where(x => !string.IsNullOrWhiteSpace(x.PropertyName));
it will converted to sql as:
WHERE [x].[PropertyName] IS NOT NULL AND ((LTRIM(RTRIM([x].[PropertyName])) <> N'') OR [x].[PropertyName] IS NULL)
or other way:
query.Where(x => string.Compare(x.PropertyName," ") > 0);
will be converted to sql as:
WHERE [x].[PropertyName] > N' '
If you want to go change the type of the collection from nullable type IEnumerable<T?> to non-null type IEnumerable<T> you can use .OfType<T>().
.OfType<T>() will remove null values and return a list of the type T.
Example: If you have a list of nullable strings: List<string?> you can change the type of the list to string by using OfType<string() as in the below example:
List<string?> nullableStrings = new List<string?> { "test1", null, "test2" };
List<string> strings = nullableStrings.OfType<string>().ToList();
// strings now only contains { "test1", "test2" }
This will result in a list of strings only containing test1 and test2.

Resources