I am developing an ASP.Net MVC 3 application using Entity Framework 4.1. For a particular complex query that I need to execute I have decided to write a raw SQL query and pass it to the built in dbSet.SqlQuery method.
I have a Service method like below where I assign the SQL query to a string variable called query. As the query is passed two parameters, I have parameterized these to prevent SQL Injection.
public IList<User> GetAvailableLocums(int shiftID, int shiftDateID)
{
var query ="Select .... where t1 = @p0 and t2 = @p1";
ObjectParameter _shiftID = new ObjectParameter("p0", shiftID);
ObjectParameter _shiftDateID = new ObjectParameter("p1", shiftDateID);
object[] parameters = new object[] { _shiftID, _shiftDateID };
return _UoW.User.GetWithRawSql(query, parameters).ToList();
}
I then pass the query and the parameters to a method in my repository which executes the query for me.
public IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
{
return dbSet.SqlQuery(query, parameters).ToList();
}
I know the query is correct as I have tested it in SQL Server Management Studio, however, I currently get the following error when I try to run this code
No mapping exists from object type System.Data.Objects.ObjectParameter
to a known managed provider native type
Does anyone have any suggestions as to how I can fix this?
Thanks for your help.
Folks
The problem was that I was using ObjectParameter to create my Parameters. I instead changed this to SqlParameter and it worked fine. See below.
Change from this
To this
And it worked. Hope this helps someone else.