Right now I am doing this in Entity Framework to filter results:
public ActionResult Index(string productName, string productDesc, string productQty)
{
var products = from p in db.Products select p;
if (!String.IsNullOrEmpty(productName))
{
products = products.Where(p=>p.ProductName.Contains(productName));
}
// similarly for other parameters and returning to view as:
return View(products);
}
I want to write a stored procedure to filter the products in database itself, before fetching it to the application.
The stored procedure is:
CREATE PROCEDURE [dbo].[usp_FilterProducts]
@ProductName varchar = null,
@ProductDesc varchar = null,
@Quantity int = null
AS
BEGIN
SET NOCOUNT ON
SELECT *
FROM [Products]
WHERE (@ProductName IS NULL OR [ProductName] LIKE @ProductName)
AND (@ProductDesc IS NULL OR [ProductDesc] LIKE @ProductDesc)
AND (@Quantity IS NULL OR [Quantity] = @Quantity)
END
I have a corresponding model class as Product
.
Is this procedure correct? If not, how should it be?
And, how do I call it from controller?