How can I use Linq to join between objects and entities? - linq

I have a collection of IDs in memory, and I would like to fetch only rows from a DB matching those IDs.
In SQL, I could either write a query like SELECT * FROM mytable WHERE id IN (1,3,5,10) or do a join between tables.
My problem is that EF can't build a query where I join my EF-data with my local array or list.
(I'm using EF4.1, but I'm guessing the problem/solution would be similar in older versions, as well as with Linq-to-SQL.)

You can use Contains() with your ID collection myIDs to generate the equivalent WHERE id IN .. query:
var results = context.mytable.Where(x => myIds.Contains(x.Id));

Related

Consecutive JOIN and aliases: order of execution

I am trying to use FULLTEXT search as a preliminary filter before fetching data from another table. Consecutive JOINs follow to further refine the query and to mix-and-match rows (in reality there are up to 6 JOINs of the main table).
The first "filter" returns the IDs of the rows that are useful, so after joining I have a subset to continue with. My issue is performance, however, and my lack of understanding of how the SQL query is executed in SQLite.
SELECT *
FROM mytbl AS t1
JOIN
(SELECT someid
FROM myftstbl
WHERE
myftstbl MATCH 'MATCHME') AS prior
ON
t1.someid = prior.someid
AND t1.othercol = 'somevalue'
JOIN mytbl AS t2
ON
t2.someid = prior.someid
/* Or is this faster? t2.someid = t1.someid */
My thought process for the query above is that first, we retrieve the matched IDs from the myftstbl table and use those to JOIN on the main table t1 to get a sub-selection. Then we again JOIN a duplicate of the main table as t2. The part that I am unsure of is which approach would be faster: using the IDs from the matches, or from t2?
In other words: when I refer to t1.someid inside the second JOIN, does that contain only the someids after the first JOIN (so only those at the intersection of prior and those for which t1.othercol = 'somevalue) OR does it contain all the original someids of the whole original table?
You can assume that all columns are indexed. In fact, when I use one or the other approach, I find with EXPLAIN QUERY PLAN that different indices are being used for each query. So there must be a difference between the two.
The query should be simplified to
SELECT *
FROM mytbl AS t1
JOIN myftstbl USING (someid) -- or ON t1.someid = myftstbl.someid
JOIN mytbl AS t2 USING (someid) -- or ON t1.someid = t2.someid
WHERE myftstbl.{???} MATCH 'MATCHME' -- replace {???} with correct column name
AND t1.othercol = 'somevalue'
PS. The query logic is not clear for me, so it is saved as-is.

Query to find DISTINCT between array of objects in Cosmos DB [ SQL API ]

I am using Azure Cosmos DB with SQL API and we need to find the DISTINCT values between array of objects in the same document.
I have structured the collection in the following ways
I have 2 main attribute RID and RNAME. In the first collection, I have only one document which contains all the RID and RNAME mapping in the array of objects.
"Details":[
{
"RID":"1",
"RNAME:"Car"
},
{
"RID":"1",
"RNAME:"Car"
}]
In second collection, I have multiple documents for each RID and RNAME mapping.
{
"RID":"1",
"RNAME:"Car"
}
I am using Stored procedure and I need to know which one is a good way to get DISTINCT of RNAME using stored procedure.
Using first collection, I am not sure how to query to find DISTINCT RNAME between objects in the array.
Using second collection. when I use the SQL editor, the distinct Query works but not sure how to put it in Stored procedure.
DISTINCT Values of RNAME
1.multiple documents
use sql:
select distinct c.RNAME from c
2.single document
use sql:
SELECT distinct d.RNAME FROM c
join d in c.Details

how to query from multiple tables in sqlite.swift

Is it possible to write a statement in sqlite.swift that will generate the equivalent sql:
SELECT foods.name, food_types.name FROM foods, food_types
WHERE foods.type_id=food_types.id LIMIT 10;
I can't figure out how to query from multiple Table objects at once.
Thanks!
Your original query passes two tables to the FROM clause, creating an implicit join. SQLite.swift's query builder language currently only supports explicit joins.
Check out the documentation under Joining Other Tables for more information on joining tables.
In your case:
let foods = Table("foods")
let food_types = Table("food_types")
let name = Expression<String>("name")
let id = Expression<Int64>("id")
let type_id = Expression<Int64>("type_id")
let query = foods
.select(foods[name], food_types[name])
.join(food_types, on: foods[type_id] == food_types[id])
.limit(10)
I figured it out. The foreign key is a column for all the tables I'm trying to join, but there are foreign key members that are not common among all the tables so I believe sql then generates a a cross join vs an inner join... That leads to all the extra rows in the query. I confirmed this by using the sql that sqlite.swift generates on the db directly.

How can I convert sql to linq

This is my SQL query
SELECT
sys.sysobjects.name Name,
sys.foreign_keys.*
FROM
sys.foreign_keys
inner join sys.sysobjects on
sys.foreign_keys.parent_object_id = sys.sysobjects.id
WHERE
referenced_object_id = OBJECT_ID(N'[dbo].[Country]')
I have installed Linqer to convert SQL to linq.
But I got an error:
SQL cannot be converted to LINQ: Table [foreign_keys] not found in the current Data Context.
I am a beginner in Linq. Can Anyone help me to convert SQL to Linq
The problem is that system views will not be picked up by Linqer. If you want to read these tables in your application, first create your own views on them, as was done here and write a query on these views.
CREATE VIEW SysObjectsView AS SELECT * FROM sys.sysobjects;
GO
CREATE VIEW SysForeignKeysView AS SELECT * FROM sys.foreign_keys;
GO
SELECT obj.name Name, fk.*
FROM SysForeignKeysView fk
INNER JOIN SysObjectsView obj ON fk.parent_object_id = obj.id
INNER JOIN SysObjectsView objfk ON fk.referenced_object_id = objfk.id
WHERE objfk.name = N'Country'
Linqer should be able to pick up these views.

Entity Framework 4 generated queries are joining full tables

I have two entities: Master and Details.
When I query them, the resulting query to database is:
SELECT [Extent2]."needed columns listed here", [Extent1]."needed columns listed here"
FROM (SELECT * [Details]."all columns listed here"...
FROM [dbo].[Details] AS [Details]) AS [Extent1]
LEFT OUTER JOIN [dbo].[Master] AS [Extent2] ON [Extent1].[key] = [Extent2].[key]
WHERE [Extent1].[filterColumn] = #p__linq__0
My question is: why not the filter is in the inner query? How can I get this query? I've tried a lot of EF and Linq expressions.
What I need is something like:
SELECT <anything needed>
FROM Master LEFT JOIN Details ON Master.key = Details.Key
WHERE filterColumn = #param
I'm having a full sequential scan in both tables, and in my production environment, I have milions of rows in each table.
Thanks a lot !!
Sometimes The entity Framework does not produce the best query. You can do a few of the following to optimize.
Modify the linq statement (test with
LINQPad)
Create a stored proc and map the stored proc to return an entity
Create a view that handles the join and map the view to a new
entity

Resources