No mapping exists from object type System.Collections.Generic.List when executing stored proc with parameters in EF 4.3

后端 未结 7 1390
旧巷少年郎
旧巷少年郎 2020-12-30 19:30

Lately I\'ve been working on stored procedure and encountered 1 strange problem.

First, I was able to successfully call a stored procedure from the database via:

相关标签:
7条回答
  • 2020-12-30 20:08

    The solution for this problem (in my case was)

     var stuff = db.Database.SqlQuery<SomeEntityType>(query, parms);
    

    Where query was a string that had parameters inserted such as @Name etc. The parms variable was a List of SQLParameters. SQL doesn't like generic lists....

    SQL must have an array of SQLParameters sent as and object[] and not a list of generic type.

    var stuff = db.Database.SqlQuery<SomeEntityType>(query, parms.ToArray());
    
    0 讨论(0)
  • 2020-12-30 20:12

    In case someone else comes across this...

    I created the parameters as a List and then in the SqlQuery call I passed it with a .ToArray(). Worked for me. Here's the modified code below...

    var parameters = new List<object>(); 
    parameters.Add(new SqlParameter("param1", param1Value)); 
    parameters.Add(new SqlParameter("param2", param2Value)); 
    IList<XXXViewModel> XXXList = 
    _context.Database.SqlQuery<XXXViewModel>("spXXX @param1, @param2", parameters.ToArray()).ToList(); 
    
    0 讨论(0)
  • 2020-12-30 20:12

    didn't state SQL Server version, but Erland Sommarskog has an article on how to use Table-Valued Parameters in SQL Server and .NET.

    http://www.sommarskog.se/arrays-in-sql-2008.html

    Able to pass a variable amount of arguments from client using a single parameter.

    0 讨论(0)
  • 2020-12-30 20:17

    You can also use string.Format to pass parameters to a stored procedure

    string command = string.Format("EXEC spXXX {0},{1}", param1Value, param2Value);
    IList<XXXViewModel> XXXList = 
      _context.Database.SqlQuery<XXXViewModel>(command).ToList();
    
    0 讨论(0)
  • 2020-12-30 20:24

    You need to pass each parameter to the method (ie You can't pass a list)

    IList<XXXViewModel> XXXList =
         _context.Database.SqlQuery<XXXViewModel>("spXXX @param1, @param2", 
         new SqlParameter("param1", param1Value), 
         new SqlParameter("param2", param2Value)).ToList();
    
    0 讨论(0)
  • 2020-12-30 20:25

    If the stored procedure is only for update/insert, the following can be used as well.

    string cmd = Constants.StoredProcs.usp_AddRoles.ToString() + " @userId, @roleIdList";
    int result = db.Database
                            .ExecuteSqlCommand
                            (
                               cmd,
                               new SqlParameter("@userId", userId),
                               new SqlParameter("@roleIdList", roleId)
                            );
    
    0 讨论(0)
提交回复
热议问题