sql query with alias name - c#

i have a table with this columns--- Or
orgid ispaid validity noofthingstoTake
1 yes 2010-06-05 20
2 yes 2010-06-09 7
i have used this query(to join two more tableS):
select distinct B.RequirementID,A.OrganizationID
from
Organization A,RequirementsDetailsforOrganization B,validityorgdet F
where A.OrganizationID=B.OrganizationID and F.orgid=A.OrganizationID and
F.ispaid=1 and F.validity>=GETDATE() and
F.noofthingstoTake> ??
but i dont know how to check the (noofthingstaken) over here. it should not exceed 20. im passing this query from my code behind page to the Sql. how to get the query excute to check it should not exceed the noofthingstaken
pls help me out....????

Try this
select distinct B.RequirementID,A.OrganizationID from
Organization A,RequirementsDetailsforOrganization B,validityorgdet F
where A.OrganizationID=B.OrganizationID and F.orgid=A.OrganizationID and
F.ispaid=1 and F.validity>=GETDATE() and F.noofthingstoTake <= 20

Presumably noofthingstoTake is actually an alias and not a column name in your table. You can't use column aliases outside of the select clause because they don't actually exist until the query is done running. So, you can't compare directly to noofthingstoTake, but must instead refer to the actual field name that that column came from. If it's an expression, just use the entire expression. Note that if it's an aggregate, you'll need to put it in a having clause, not a where clause.
(Note: You really should have posted your entire query)

Related

What is the difference between these two LINQ Queries and how to correctly optimize them?

I have a Clients table which has the following columns:
Id, FirstName, LastName, CurrencyId, Gender.
I want to select the client's Currency that corresponded to Id 10 so I am doing something like this:
var currencyId = Db.Clients.FirstOrDefault(c=>c.Id == 10)?.CurrencyId;
Does this line bring all properties from Db and selects the currency in the code or it executes something like this in the database:
SELECT currencyId FROM Client WHERE ID = 10
Or I should write the linq like this:
var currencyId = Db.Clients.Where(c=>c.Id == 10).Select(c=>c.CurrnecyId).FirstOrDefault();
What's the difference between the two queries?
And what is the correct way to translate the above SQL query into a linq query?
Looked into it myself cause I found the anwser from most people questionable. I expect the FirstOrDefault to materialize the result (you also see from the type that you are not longer working with a query object), so that would mean it queries for all properties.
Unlike the 2nd query where you are still working with a query when filtering the property you like, thus dependent on the implementation it could be used for filtering properties and selecting specific fields.
The following is an example of the queries generated using EF for two similar queries, where it shows both generating different queries: https://dotnetfiddle.net/5aFJAZ
In your first example, var currencyId = Db.Clients.FirstOrDefault(c=>c.Id == 10)?.CurrencyId; the query selects the entire object to memory and then returns the Id property from that in memory object. As a result it needs to do something like the following SQL: SELECT * FROM Clients WHERE Id = 10. I understand I'm not using a parameter here and EF does spell out every column. However the key to understand here is that by returning more columns than you need, you potentially are setting up a performance concern because a covering index on Id and CurrencyId would not be used.
Your second LINQ query would use a SQL statement like SELECT CurrencyId FROM Clients Where Id = 10 which would take advantage of your indexes assuming you have an index covering these columns.

is there a better performance's way to get only few columns in ASP MVC without getting the whole table and filter it with LinQ?

im calling a table with 200.000 rows and 6 columns, but i only want 2 of these columns to be used in one controller, so i want to know if there is a better way to call them from the server without compromising performance, because as i know Linq queries get the whole table and them makes the filtering, i think maybe Views is a good way, but i want to know if there are others and betters, Thanks.
for example:
var items = from i in db.Items select new {i.id,i.name};
in case i have 1.000.000 items, will it be a trouble for the server?
Your initial assumption is incorrect.
In general LINQ queries do not get the whole table. the query is converted into a "server side expression" (i.e. a SQL statement) and the statement is resolved on the server and only the requested data is returned.
Given the statement you provided you will return only two columns but you will get 1,000,000 objects in the result if you do not do any filtering. But that isn't a problem with LINQ, that's a problem with you not filtering. If you included a where clause you would only get the rows you requested.
var items = from i in db.Items
where i.Whatever == SomeValue
select new { i.id, i.name };
Your original query would be translated (roughly) into the following SQL:
SELECT id, name FROM Items
You didn't include a where clause so you're going to get everything.
With the version that included a where clause you'd get the following SQL generated:
SELECT id, name FROM Items WHERE Whatever = SomeValue
Only the rows that match the condition would be returned to your application and converted into objects.

Selecting Consecutive String Entries with LINQ to Entities

At first you might think this is duplicate of this question but hopefully you will see it is not.
I also want to select groups of rows that are consecutive but consider that this time the entries are telephone numbers, therefore, stored as string.
I have been trying somethink like:
var numbers = await (from a in context.Telephones
from b in context.Telephones
Convert.ToInt32(a.Number) < Convert.ToInt32(b.Number) &&
Convert.ToInt32(b.Number) < (Convert.ToInt32(a.Number) + numberQuantity)
group b by new { a.Number }
into myGroup
where myGroup.Count() + 1 == numberQuantity
select myGroup.Key.Number).ToListAsync();
But this fails with:
LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.
I understand that LINQ to Entities does not support Convert.ToInt32 but I am running out of ideas here to make it work.
So if my database has:
2063717608
2063717609
2063717610
2063717611
2063717613
2063717614
How can I select consecutive rows based on the string values? And when querying for 3 consecutive numbers get results like:
From 2063717608 to 2063717610
From 2063717609 to 2063717611
1- If you are aware of performance side effect of calling AsEnumerable() cast your query and do conversion in memory on the retrieved entities.
2- If you don't want solution #1, you have to look for a way to solve the conversion problem:
2-1- Either change the column type in the database to int
2-2- Or select one of the solution previously proposed by other developers such as:
Problem with converting int to string in Linq to entities

Dynamic where clause in linq query

Sorry for my bad English. I have a problem. I want to create dynamic where clause in a LINQ query. I have one list object name "list1" having values Country, City, State and one datatable that has column named Name, Lastname, Country, City, State. I want to compare list1 values with datatable columns and get null / empty rows.
So I want a LINQ query like this:
var query = from p in datatable.AsEnumerable()
where list1 == null
select p
but it returns an error. How can I solve this problem?
Thanks in advance.
Ok, let's get going - your query is ridiculously bad.
You should not have datatable.AsEnumerable - that forces a table scan (running through the whole table).
Second, you have to code all fields expressively. This is going to get nasty - per definition Depending on size of list this will be very bad.
In general, every query is an IQueryable itself, so you can chain where conditions.VERY nice - I use that partially myself, defining the core query, then adding additional where clauses as needed (by input parameter) before executing.
Sadly, comparing a table against a list of elements by individual field match is as bad as it gets from the sql level.

LINQ join behaving oddly

I am attempting to perform a join between two tables and limit results by 3 conditions. 2 of the conditions belong to the primary table, the third condition belongs to the secondary table. Here is the query I'm attempting:
var articles = (from article in this.Context.contents
join meta in this.Context.content_meta on article.ID equals meta.contentID
where meta.metaID == 1 && article.content_statusID == 1 && article.date_created > created
orderby article.date_created ascending
select article.content_text_key);
It is meant to join the two tables by the contentID, then filter based on the metaID (type of article), statusID, and then get all articles that are greater than the datetime created. The problem is that it returns 2 records (out of 4 currently). One has a date_created less than created and the other is the record that produced created in the first place (thus equal).
By removing the join and the where clause for the meta, the result produces no records (expected). What I can't understand is that when I translate this join into regular SQL it works just fine. Obviously I'm misunderstanding what the functionality of join is in this context. What would cause this behavior?
Edit:
Having tried this in LinqPad, I've noticed that LinqPad provides the expected results. I have tried these queries separately in code and it isn't until the join is added that odd results begin populating it appears to be happening on any date comparison where the record occurs on the same day as the limiter.
I can't seem to be able to add a comment but in debug mode you should be able to put a break point on this line of code. When you do you should be able to hover over it and have it tell you the sql that LINQ generates. Please post that sql.
At your suggestion, I'm posting my comment as the answer:
"It might also help to see your schema. The data types for metaID,
content_statusID, and date_created might come into play as well -- and
it's easy for me (somebody who's unfamiliar with your code) to make
assumptions about those data types."

Categories

Resources