问题
我收到错误
过程或函数spAddDepartment指定了太多参数
如何解决?
详细信息:在ASP.NET MVC 5中使用流畅的api使用存储过程department
将数据插入表spAddDepartment
时,我得到了上面提到的错误。
表Departments
:
CREATE TABLE [dbo].[Departments]
(
[DepartmentID] [int] IDENTITY(1,1) NOT NULL,
[DepartmentName] [nvarchar](50) NULL,
[IsActive] [bit] NULL
)
存储过程spAddDepartment
:
ALTER Procedure [dbo].[spAddDepartment]
@DepartmentName nvarchar(50)
AS
BEGIN
INSERT INTO Departments
VALUES (@DepartmentName, 1)
END
Department
模特课:
public partial class Department
{
public Department()
{
Employees = new HashSet<Employee>();
}
public int DepartmentID { get; set; }
[StringLength(50)]
public string DepartmentName { get; set; }
public bool? IsActive { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
数据库上下文:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Department>()
.MapToStoredProcedures(p => p.Insert(sp => sp.HasName("spAddDepartment").Parameter(pm => pm.DepartmentName, "DepartmentName")));
}
DepartmentController
:
[HttpPost]
public ActionResult Insert(Department depart)
{
depart.IsActive = true;
hr.Departments.Add(depart);
hr.SaveChanges();
return View(depart);
}
部门观点:
<div class="form-horizontal">
<h4>Department</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.DepartmentName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.DepartmentName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.DepartmentName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.IsActive, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.IsActive)
@Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
答案 0 :(得分:1)
执行SaveChanges()
时,它会调用数据库(假设DepartmentName
为Dep1
:
exec [dbo].[spAddDepartment] @DepartmentName=N'Dep1',@IsActive=1
这就是您收到错误的原因,因为您的存储过程只有1个参数,但EF正在寻找带有2个参数的存储过程。
你问为什么2个参数?因为您的类有4个属性:一个是虚拟的,因此忽略一个,DepartmentID
是标识列,因此一个将自动生成,因此不需要,另外两个属性(DepartmentName
和{{ 1}})是必需的,因此它需要一个带有2个参数的存储过程,如上所示。
<强>修正强>
要解决此问题,请在存储过程中添加另一个参数。