在Entity Framework中如何编写参数化的in-in raw SQL查询?我尝试过以下操作:
string dateQueryString = String.Join(",",chartModelData.GetFormattedDateList()); //Dates returned in format of 20140402,20140506,20140704 const string selectQuery = @"SELECT MAX(DATA_SEQ) AS MaxSeq,MIN(DATA_SEQ) AS MinSeq,COUNT(1) AS TotSampleCnt FROM SPCDATA_TB WHERE DATA_WDATE IN @DateParam AND LINE_CODE = @LineCode AND MODEL_NO = @ModelNumber AND LOT_NO = @LotNumber AND EQUIP_NO LIKE @EquipNumber"; SPCDataSeqCntInfo dataSeqCntInfo = _dbContext.Database.sqlQuery<SPCDataSeqCntInfo>(selectQuery,new sqlParameter("@DateParam",dateQueryString),new sqlParameter("@LineCode",chartModelData.LineCode),new sqlParameter("@ModelNumber",chartModelData.ModelNum),new sqlParameter("@EquipNumber",equipmentNumber),new sqlParameter("@LotNumber",chartModelData.LotNum)) .SingleOrDefault() ?? new SPCDataSeqCntInfo();
但是如预期的那样,它会在DateParam上抛出一个错误,因为它期待一个单一的值.
解决方法
这不是特定于实体框架的问题,您可以通过动态生成自己的参数名称来解决这个问题.
var parameters = new List<sqlParameter> { new sqlParameter("@DateParam",chartModelData.LotNum) }; var dateParameters = chartModelData .GetFormattedDateList() .Select((date,index) => new sqlParameter("@date" + index,date)); parameters.AddRange(dateParameters); var inValues = string.Join(",dateParameters.Select(p => p.ParameterName)); var query = @"SELECT MAX(DATA_SEQ) AS MaxSeq,COUNT(1) AS TotSampleCnt FROM SPCDATA_TB WHERE DATA_WDATE IN (" + inValues + @") AND LINE_CODE = @LineCode AND MODEL_NO = @ModelNumber AND LOT_NO = @LotNumber AND EQUIP_NO LIKE @EquipNumber"; var myResult = _dbContext.Database .sqlQuery<SPCDataSeqCntInfo>(query,parameters.ToArray());
SELECT MAX(DATA_SEQ) AS MaxSeq,COUNT(1) AS TotSampleCnt FROM SPCDATA_TB WHERE DATA_WDATE IN (@date0,@date1,@date2) AND LINE_CODE = @LineCode AND MODEL_NO = @ModelNumber AND LOT_NO = @LotNumber AND EQUIP_NO LIKE @EquipNumber