-1
db.Products.SqlQuery("SELECT * FROM Products WHERE Name LIKE '%{0}%' AND ORDER BY Name OFFSET 0 ROWS FETCH NEXT {1} ROWS ONLY", str, 10).ToList();

On SQL Server, this query returns results, but it's not using Entity Framework

4

1 Answer 1

1

This should work. Note that the 1st parameter is a string parameter value where the value is surrounded by the wild card % character and it is not enclosed in quotes in the query itself because it will be replaced by a proper parameter. The next 10 offset can't be parameterized but you could use the .Skip and .Take extensions to do this instead on the returned result set. In the query below I hand coded the value. I also removed the extra AND you had.

db.Products.SqlQuery("SELECT * FROM Products WHERE Name LIKE {0} ORDER BY Name OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY", "%" + str + "%").ToList();

With Skip/Take

var top10 = db.Products.SqlQuery("SELECT * FROM Products WHERE Name LIKE {0} ORDER BY Name", "%" + str + "%").Skip(0).Take(10).ToList();

And here is the same functional query that does not use SqlQuery

var top10 = db.Products.Where(prod => prod.Name.Contains(str))
    .OrderBy(x => x.Name)
    .Skip(0) // not necessary because of value 0 but illustrates how to skip records
    .Take(10)
    .ToList();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.