How to Write In Clause with EF FromSql?

最后都变了- 提交于 2019-12-02 09:56:12

问题


I have an unknown amount of parameters for my inclause. How can I write it so it works with EF Core?

  var formattedValues = String.Join(",", values.Select(s => "'" + s + "'"));
            var identifierParam = new SqlParameter("jsonColumn", $"$.{identifierKey}");
            var filterValueParam = new SqlParameter("value", $"%{formattedValues}%");

            var items = dbContext.Items.FromSql("select * FROM Items WHERE  AND JSON_VALUE(Attributes, @jsonColumn) in (@value)", filterValueParam, identifierParam).ToList();

I think it is because each value in the in clause needs it's own Parameter.


回答1:


Since you're using SQL Server, you can pass the list of values as JSON. EG

  var jsonValues = JsonConvert.SerializeObject(values.ToList());
  var filterValueParam = new SqlParameter("@values", jsonValues );
  var identifierParam = new SqlParameter("@jsonColumn", $"$.{identifierKey}");

  var sql = "select * FROM Items WHERE  AND JSON_VALUE(Attributes, @jsonColumn) in (select value from openjson(@values))";

  var items = dbContext.Items.FromSql(sql, filterValueParam, identifierParam).ToList();


来源:https://stackoverflow.com/questions/53016130/how-to-write-in-clause-with-ef-fromsql

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