[英]Use stored procedure in C# and ASP.NET MVC
I have an ASP.NET MVC application that uses an EF model (database-first approach). 我有一个使用EF模型(数据库优先方法)的ASP.NET MVC应用程序。 I have stored procedures defined in SQL Server that I need to use in my application.
我已经在SQL Server中定义了需要在应用程序中使用的存储过程。 I've never done this before, any guidance regarding this will be appreciated.
我以前从未做过,对此的任何指导将不胜感激。 I did add the stored procedure and create the function for it but have no idea on how to add it to my controllers and views.
我确实添加了存储过程并为其创建了函数,但是不知道如何将其添加到控制器和视图中。 For the code provided below, I simply want to add a card.
对于下面提供的代码,我只想添加一张卡。
Stored procedure: 存储过程:
CREATE PROCEDURE [dbo].[CreateLoyaltyCards]
@NumberOfCards AS integer,
@CustomerID AS integer
AS
BEGIN
SET NOCOUNT ON;
DECLARE @NumberOfRows as integer = 0;
DECLARE @LoopNumber as integer = 0
WHILE @LoopNumber < @NumberOfCards
BEGIN
INSERT INTO Cards (CustomerID, CardDate)
VALUES (@CustomerID, GetDate())
SET @LoopNumber = @LoopNumber + 1
END
SELECT
Customers.CustomerCompanyName, Cards.CardNumber
FROM
Customers
INNER JOIN
Cards ON Customers.CustomerID = Cards.CustomerID
WHERE
Customers.CustomerID = @CustomerID
ORDER BY
CardID ASC
OFFSET @NumberOfRows ROWS
FETCH NEXT @NumberOfCards ROWS ONLY
END
CardsController // this is where I need to use the stored procedure CardsController //这是我需要使用存储过程的地方
public ActionResult Create()
{
ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "CustomerCompanyName");
return View();
}
// POST: Cards/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CardID,CardNumber,CustomerID,StoreCustomerID,CardDate,CardStatus,CardNumber2,DiscountLevelID,LoyaltyLevelID,GiftCardEnabled,LoyaltyEnabled")] Card card)
{
if (ModelState.IsValid)
{
db.Cards.Add(card);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "CustomerCompanyName", card.CustomerID);
return View(card);
}
This is the stored procedure in context class 这是上下文类中的存储过程
public virtual ObjectResult<Card> CreateCards(Nullable<int> numberOfCards, Nullable<int> customerID)
{
var numberOfCardsParameter = numberOfCards.HasValue ?
new ObjectParameter("NumberOfCards", numberOfCards) :
new ObjectParameter("NumberOfCards", typeof(int));
var customerIDParameter = customerID.HasValue ?
new ObjectParameter("CustomerID", customerID) :
new ObjectParameter("CustomerID", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Card>("CreateCards", numberOfCardsParameter, customerIDParameter);
}
You just need to create object of EF class and call directly the function(created from SP). 您只需要创建EF类的对象并直接调用从SP创建的函数即可。
eg suppose context is your object. 例如,假设上下文是您的对象。
context.CreateCards(numberOfCards, customerID);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.