问题
我收到错误
Procedure or function spAddDepartment has too many arguments specified
如何解决?
详细信息:在 ASP.NET MVC 5 中使用 Fluent api 使用存储过程 spAddDepartment
将数据插入表 department
时,出现上述错误。
表部门
:
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
部门
模型类:
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")));
}
部门 Controller
:
[HttpPost]
public ActionResult Insert(Department depart)
{
depart.IsActive = true;
hr.Departments.Add(depart);
hr.SaveChanges();
return View(depart);
}
部门 View :
<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>
最佳答案
当您执行SaveChanges()
时,它将调用数据库(假设DepartmentName
是Dep1
:
exec [dbo].[spAddDepartment] @DepartmentName=N'Dep1',@IsActive=1
这就是您收到错误的原因,因为您的存储过程只有 1 个参数,但 EF 正在寻找具有 2 个参数的存储过程。
你问为什么有2个参数?因为您的类有 4 个属性:一个是虚拟属性,因此会被忽略,DepartmentID
是标识列,因此将自动生成一个属性,因此不需要,其他 2 个属性 (DepartmentName
和 IsActive
) 是必需的,因此它需要一个带有 2 个参数的存储过程,如上所示。
修复
要解决此问题,请向存储过程添加另一个参数。
关于c# - 过程或函数 SpAddDepartment 指定的参数过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48835346/