Entity Framework Core- passing parameters to Where IN Clause Raw Query

心不动则不痛 提交于 2021-02-11 06:25:20

问题


I just want to select data for range of values from db. e.g. "SELECT * from VwCampaigns where PmcId in (1,2,3)"

This is my code in Entity Core

_dbContext.CampaignsView.FromSql("SELECT * from VwCampaigns where PmcId in ({1})", pmcIds).ToList()

How to pass range of integer in raw query? Please Help


回答1:


I do not think there is any way to do it by passing a list of Ids as a parameter because EF tries to interpret it as a single parameter. What worked for me was the following:

Given a list of IDs: 1,2,3

Convert the list into an array of objects so that you can pass as an argument into FromSql as that accepts params object[] and EF core will treat them as separate parameters.

Construct a query that will create separate parameters for each item in the list of IDs so that you end up with a query that looks like the following:

"SELECT * from VwCampaigns where PmcId in ({0},{1},{2})"

My working code:

var pmcIds = new List<int> { 1,2,3 }.Select(x => (object)x).ToArray();
var sqlQuery = $"SELECT * FROM dbo.VwCampaigns WHERE Id in ({string.Join(',', pmcIds.Select(x => $"{{{Array.IndexOf(pmcIds, x)}}}"))})";

var results = _dbContext.CampaignsView.FromSql(sqlQuery, pmcIds).ToList();

Alternatively you can use a SQL command like so: Mark Byers' Answer




回答2:


Alternative orm tool ? For Visit https://dapper-tutorial.net/querymultiple



来源:https://stackoverflow.com/questions/58950476/entity-framework-core-passing-parameters-to-where-in-clause-raw-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!