【问题标题】:How to add list to SQL query?如何将列表添加到 SQL 查询?
【发布时间】:2018-12-10 20:18:04
【问题描述】:

我传递了一个参数month 并附加到一个列表中。

如何将列表添加到SqlQuery 参数?

错误:不存在从对象类型 System.Collections.Generic.List`1[] 到已知托管提供程序本机类型的映射。

public ActionResult filterhre(int? month, int? year)
{
    List<int> lst = new List<int>();

    for (int i = 1; i <= @month; i++)
    {
        lst.Add(i);
    }

    ViewBag.location_fraud_year = db.Database.SqlQuery<YearCheck>(@"SELECT fraud_location, count(claim_amount) as counting_claim, sum(claim_amount) as counting_sum FROM testtable
where month(datelocation) in ({0}) and year(datelocation)={1} and fraud_location is not null ",lst, year).ToList(); 
}

型号:

public class YearCheck
{
    public string fraud_location { get; set; }
    public int? counting_claim { get; set; }
    public decimal? counting_sum { get; set; }
}

【问题讨论】:

  • location_fraud_year 的类型是什么?您是否有从List&lt;int&gt; 转换为它的类型的隐式转换?
  • "where month(datelocation) &lt; {0}" 就够了

标签: c# sql .net


【解决方案1】:

正如错误消息告诉您的那样,.Net 不知道如何将您的列表转换为 SQL 中的逗号分隔列表。你必须自己做:

ViewBag.location_fraud_year = db.Database.SqlQuery<YearCheck>(@"...", String.Join(",", names.ToArray()), year).ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    相关资源
    最近更新 更多