当我需要传递单个参数时,我可以轻松完成,如下所示:
public ProjectsModel GetProjectListBySearch(int projectId) { try { using (_context = new Exo_ADBEntities()) { var getdetailprojectlist = _context.Database.sqlQuery<ProjectsModel>("exec dbo.[GetProjectListByID] @ProjectID",new sqlParameter("@ProjectID",projectId)).FirstOrDefault(); return getdetailprojectlist; } } catch (Exception) { throw; } }
这很好用,但是当我尝试做同样的事情但传递两个参数时我发现语法错误称为无效参数请帮我做这个.使用两个参数时的代码如下
public List<ProjectsModel> GetProjectDetailsBySectorAndSubSector(int sectorid,int subsectorid) { try { using (_context = new Exo_ADBEntities()) { var projectbysectorandsubsector = _context.Database.sqlQuery<ProjectsModel>("exec dbo.[GetProjectDetailsBySectorAndSubSector] @sectorId,@subSectorId",new sqlParameter("@sectorId,sectorid,subsectorid)).ToList(); return projectbysectorandsubsector; } } catch (Exception) { throw; } }
解决方法
问题是您尝试将多个参数作为单个对象传递.
如果您使用look at the signature的Database.sqlQuery,您会看到:
public DbRawsqlQuery<TElement> sqlQuery<TElement>( string sql,params Object[] parameters )
这太基础了,但是,当你在C#函数中看到params时,它意味着“任意数量的参数”.这意味着您可以根据需要传递尽可能多的参数.所以,在你的情况下,它就像这样:
_context.Database.sqlQuery<ProjectsModel>( "exec dbo.[GetProjectDetailsBySectorAndSubSector] @sectorId,new sqlParameter("@sectorId",sectorid),new sqlParameter("@subSectorId",subsectorid) ).ToList()
请注意,当您找到params Object []时,您也可以传递一个数组而不是几个参数,即
_context.Database.sqlQuery<ProjectsModel>( "exec dbo.[GetProjectDetailsBySectorAndSubSector] @sectorId,new Object[] { new sqlParameter("@sectorId",subsectorid)} ).ToList()
根据代码的外观,这可能更方便.