我有一个MVC应用程序需要调用数据库中的存储过程。该功能基本上允许用户选择商店并输入他们想要为该商店生成的卡的数量。我的代码的工作原理是它插入并生成这些卡但是它仍然存在这个错误:“数据读取器与指定的'GiftworxModel.Card'不兼容。类型的成员'CardID'没有相应的列在同名的数据阅读器中。“创建卡后,控制器方法也不会重定向到索引。
上下文类:
public virtual ObjectResult<Card> CreateCards(Nullable<int> numberOfCards, Nullable<int> customerID, MergeOption mergeOption)
{
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", mergeOption, numberOfCardsParameter, customerIDParameter);//This is where the code breaks
}
控制器方法:
public ActionResult Create()
{
ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "CustomerCompanyName");
return View();
}
// POST: Cards/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Card card, int? numberOfCards, int?customerId)
{
var cards = db.CreateCards(numberOfCards, customerId).ToList();
ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "CustomerCompanyName", card.CustomerID);
return RedirectToAction("Index", "Cards");
}
查看:
@using (Html.BeginForm("Create", "Cards", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<form role="form">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.CardID)
<div class="form-group">
<label>Store</label>
@Html.DropDownList("CustomerID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CustomerID, "", new { @class = "text-danger" })
</div>
<div class="form-group">
Number of Cards: <input type="text" name="numberOfCards"/>
</div>
<input type="submit" value="Create" class="btn btn-default" style="background-color: #0a9dbd; color: white;" />
}
存储过程:
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
答案 0 :(得分:0)
根据您获得的错误:
数据阅读器与指定的GiftworxModel.Card不兼容。类型为CardID的成员在数据读取器中没有相应的列具有相同的名称
CardID
类中有GiftworxModel.Card
个属性,但您没有从存储过程返回CardID
。只是尝试从存储过程传递CardID。所以基本上你的存储过程结果集应该返回GiftworxModel.Card
类中的所有字段。
答案 1 :(得分:0)
您正尝试将存储过程结果映射到“Card”对象,但映射失败。我无法确定,因为我看不到存储过程返回的选择,但是您没有返回“卡”结果,或者您没有返回它的所有属性(例如:错误中的CardID)