How to use DbContext.Database.SqlQuery(sql, params) with stored procedure? EF Code First CTP5

后端 未结 10 1877
梦谈多话
梦谈多话 2020-11-22 16:53

I have a stored procedure that has three parameters and I\'ve been trying to use the following to return the results:

context.Database.SqlQuery

        
10条回答
  •  余生分开走
    2020-11-22 17:35

    I had the same error message when I was working with calling a stored procedure that takes two input parameters and returns 3 values using SELECT statement and I solved the issue like below in EF Code First Approach

     SqlParameter @TableName = new SqlParameter()
            {
                ParameterName = "@TableName",
                DbType = DbType.String,
                Value = "Trans"
            };
    
    SqlParameter @FieldName = new SqlParameter()
            {
                ParameterName = "@FieldName",
                DbType = DbType.String,
                Value = "HLTransNbr"
            };
    
    
    object[] parameters = new object[] { @TableName, @FieldName };
    
    List x = this.Database.SqlQuery("EXEC usp_NextNumberBOGetMulti @TableName, @FieldName", parameters).ToList();
    
    
    public class Sample
    {
        public string TableName { get; set; }
        public string FieldName { get; set; }
        public int NextNum { get; set; }
    }
    

    UPDATE: It looks like with SQL SERVER 2005 missing EXEC keyword is creating problem. So to allow it to work with all SQL SERVER versions I updated my answer and added EXEC in below line

     List x = this.Database.SqlQuery(" EXEC usp_NextNumberBOGetMulti @TableName, @FieldName", param).ToList();
    

提交回复
热议问题