Select "IN" in LINQ to SQL

I get a list of objects to update, and I have their identifiers. I want to get the source data from a database, so I:

String[] ids = updatedEvents.Select(ue => ue.id).ToArray(); var originalEventsToUpdate = Db.tbl_ffk_event .Where(e => ids.Contains(e.id)) .ToArray(); 

But what I get using the log is the generated SQL:

 SELECT [t0].[id], [t0].[fs_mapping_id], [t0].[fs_id_value], [t0].[desc] FROM [dbo].[tbl_ffk_event] AS [t0] WHERE 0 = 1 -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1 

And this SQL means "get the whole table".

How can I create an "IN" like this:

 SELECT [t0].[id], [t0].[fs_mapping_id], [t0].[fs_id_value], [t0].[desc] FROM [dbo].[tbl_ffk_event] AS [t0] WHERE [t0].[id] IN ('aaa','bbb','ccc','ddd','eee',) 

Thanks in advance.

EDIT:

I feel stupid, I have not seen WHERE 0 = 1 . This is because at that moment where there is nothing in the ids collection. I have now checked for item availability, and SQL is generated correctly. Unfortunately.

+4
source share
3 answers

Actually, due to the WHERE 0 = 1 this SQL will return an empty recordset (i.e., it is correctly displayed in terms of a schema, but without rows).

The code you give seems to be correct, but something convinced the query provider that there could never be a matching line.

Assuming this is incorrect, I would look at the column mapping for the id property. Does this comply with the database rule?

+2
source

Your list is probably empty, this is normal Linq behavior.

0
source

Try the following:

 Dim strval As String = "" Dim strnum(30) As String strval = "1,2,3,4,5,6,7,9" strnum = strval.split(",") originalEventsToUpdate = (from a in Db.tbl_ffk_event where strnum.contains(a.id) select a).tolist 
0
source

Source: https://habr.com/ru/post/1345528/


All Articles