string datequeryString = String.Join(",",chartModelData.GetFormattedDateList());//Dates returned in format of 20140402,20140506,20140704const 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());
发送到sql Server的结果查询将如下所示:
SELECT MAX(DATA_SEQ) AS MaxSeq,COUNT(1) AS TotSampleCntFROM SPcdaTA_TBWHERE DATA_WDATE IN (@date0,@date1,@date2) AND liNE_CODE = @lineCodeAND MODEL_NO = @ModelNumberAND LOT_NO = @LotNumberAND EQUIP_NO liKE @EquipNumber
一般来说,你想避免在编写查询时进行字符串 *** 作,但是我相信这个例子是从sql-injection安全的.
总结以上是内存溢出为你收集整理的c# – 如何在Entity Framework中编写一个参数化的in-in raw sql查询全部内容,希望文章能够帮你解决c# – 如何在Entity Framework中编写一个参数化的in-in raw sql查询所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)