繁体   English   中英

MVC数据库首先出现存储过程错误无法将类型为“ System.Boolean”的对象转换为类型为“ System.String”的对象

[英]MVC Database first with stored procedure error Unable to cast object of type 'System.Boolean' to type 'System.String'

我正在尝试创建将使用数据库优先方法的MVC应用程序。 (现有数据库)我遵循了在网上找到的教程,并映射了CRUD过程。 在创建时,我收到错误消息: 无法将类型为“ System.Boolean”的对象转换为类型为“ System.String”。

这是程序

    CREATE PROCEDURE [dbo].[usp_AddAdminUser]

@AdminID nvarchar(15),
@PersonName nvarchar(50),
@Email nvarchar(50),
@RoleID tinyint,
@ReceiveNotifications bit

AS

SET NOCOUNT ON

DECLARE @Message varchar(100)

IF EXISTS(SELECT PersonName FROM dbo.AdminUsers WHERE AdminID = @AdminID)
    BEGIN

        SET @Message = 'A user with this ID already exists'
    END
ELSE
    BEGIN
        INSERT
            dbo.AdminUsers
        VALUES
        (
            @AdminID,
            @PersonName,
            @Email,
            @RoleID,
            @ReceiveNotifications,
            0,
            0
        )

        DECLARE @salt UNIQUEIDENTIFIER=NEWID()
        DECLARE @Len int
        DECLARE @Min tinyint 
        DECLARE @Range tinyint  
        DECLARE @Exclude varchar(50)
        DECLARE @Char char
        DECLARE @Password nvarchar(20)

        SET @Len = 12
        SET @Min = 35
        SET @Range = 74
        SET @Exclude  = '0:;`0l1-<>/\[]()'''
        SET @Password = ''

        -- Create a temporary password
        WHILE @Len > 0
            BEGIN
                SELECT @Char = char(ROUND(RAND() * @Range + @Min,0))
                IF CHARINDEX(@Char,@Exclude) = 0 
                    BEGIN
                        SET @Password = @Password + @Char
                        SET @Len = @Len -1
                    END
            END
        INSERT
            dbo.AdminLogins
        VALUES
        (
            @AdminID,
            HASHBYTES('SHA2_512',@Password+CAST(@salt as nvarchar(36))),
            @salt
        )

        --SET @Message = 'here is your temporary password ' + @Password
    END 
--SELECT @Message AS Message



Exec msdb.dbo.sp_send_dbmail @profile_name='email',
@recipients= @Email,
@subject='Your account has been created',
@body=@Message

这是模型

    namespace AMS_MVC.Models
{
    using System;
    using System.Collections.Generic;

    public partial class AdminUser
    {
        public AdminUser()
        {
            this.Departments = new HashSet<Department>();
            this.Districts = new HashSet<District>();
            this.Divisions = new HashSet<Division>();
            this.Regions = new HashSet<Region>();
            this.Zones = new HashSet<Zone>();
            this.Locations = new HashSet<Location>();
        }

        public string AdminID { get; set; }
        public string PersonName { get; set; }
        public string Email { get; set; }
        public byte RoleID { get; set; }
        public bool ReceiveNotifications { get; set; }
        public bool ChangePW { get; set; }
        public bool Deactivated { get; set; }

        public virtual AdminLogin AdminLogin { get; set; }
        public virtual Role Role { get; set; }
        public virtual ICollection<Department> Departments { get; set; }
        public virtual ICollection<District> Districts { get; set; }
        public virtual ICollection<Division> Divisions { get; set; }
        public virtual ICollection<Region> Regions { get; set; }
        public virtual ICollection<Zone> Zones { get; set; }
        public virtual ICollection<Location> Locations { get; set; }
    }
}

这是控制器代码

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using AMS_MVC.Models;

namespace AMS_MVC.Controllers
{
    public class AdminUsersController : Controller
    {
        private MVC_AMSEntities1 db = new MVC_AMSEntities1();


        // GET: AdminUsers
        public ActionResult Index()
        {
            var adminUsers = db.AdminUsers.Include(a => a.AdminLogin).Include(a => a.Role);
            return View(adminUsers.ToList());
        }

        // GET: AdminUsers/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            AdminUser adminUser = db.AdminUsers.Find(id);
            if (adminUser == null)
            {
                return HttpNotFound();
            }
            return View(adminUser);
        }



        // GET: AdminUsers/Create
        public ActionResult Create()
        {
            ViewBag.AdminID = new SelectList(db.AdminLogins, "AdminID", "AdminID");

            ViewBag.RoleID = new SelectList(db.Roles, "RoleID", "RoleName");
            return View();
        }

        // POST: AdminUsers/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "AdminID,PersonName,Email,RoleID,ReceiveNotifications")] AdminUser adminUser)
        //public ActionResult Create()
        {
            if (ModelState.IsValid)
            {
                db.AdminUsers.Add(adminUser);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.AdminID = new SelectList(db.AdminLogins, "AdminID", "AdminID", adminUser.AdminID);
            ViewBag.RoleID = new SelectList(db.Roles, "RoleID", "RoleName", adminUser.RoleID);
            return View(adminUser);
        }

        // GET: AdminUsers/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            AdminUser adminUser = db.AdminUsers.Find(id);
            if (adminUser == null)
            {
                return HttpNotFound();
            }
            ViewBag.AdminID = new SelectList(db.AdminLogins, "AdminID", "AdminID", adminUser.AdminID);
            ViewBag.RoleID = new SelectList(db.Roles, "RoleID", "RoleName", adminUser.RoleID);
            return View(adminUser);
        }

        // POST: AdminUsers/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "AdminID,PersonName,Email,RoleID,ReceiveNotifications,ChangePW,Deactivated")] AdminUser adminUser)
        {
            if (ModelState.IsValid)
            {
                db.Entry(adminUser).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.AdminID = new SelectList(db.AdminLogins, "AdminID", "AdminID", adminUser.AdminID);
            ViewBag.RoleID = new SelectList(db.Roles, "RoleID", "RoleName", adminUser.RoleID);
            return View(adminUser);
        }

        // GET: AdminUsers/Delete/5
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            AdminUser adminUser = db.AdminUsers.Find(id);
            if (adminUser == null)
            {
                return HttpNotFound();
            }
            return View(adminUser);
        }

        // POST: AdminUsers/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            AdminUser adminUser = db.AdminUsers.Find(id);
            db.AdminUsers.Remove(adminUser);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

这是创建视图的代码

@model AMS_MVC.Models.AdminUser

@{
    ViewBag.Title = "Create Admin User";
}

<h2>Admin User Control Panel</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Create Admin User</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.AdminID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AdminID, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.AdminID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PersonName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PersonName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PersonName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.RoleID, "RoleID", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("RoleID", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.RoleID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ReceiveNotifications, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.ReceiveNotifications)
                    @Html.ValidationMessageFor(model => model.ReceiveNotifications, "", 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>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

这是过程映射映射过程的图像

我知道该程序有效,因为我可以在SSMS中运行它。 这把我逼上了墙。 我已经在这个问题上工作了近一个月了。 我做过的所有Google搜索都没有任何帮助。 我真的需要一些想法来解决这个问题。

在使用下面提到的详细方法之前,请阅读答案末尾提到的其他方法,该方法可以在很短的时间内以最少的代码更改来解决您的问题。

将标记中的adminUser.ReceiveNotifications编辑器更改为下面给出的内容,即删除发出该属性的编辑器的标记。

<input id="recNotifications" name="recNotifications" value="false"  type="checkbox" />

然后将“创建”操作方法更改为下面给出的方法。 您会注意到,将一个额外的参数用于从复选框接收布尔值被添加到该方法中,并且还会添加一行代码来设置adminUser.ReceiveNotifications属性。

  // POST: AdminUsers/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "AdminID,PersonName,Email,
      RoleID")] AdminUser adminUser, bool recNotifications = false)
    //public ActionResult Create()
    {
        //add the line below and also the extra parameter below
        adminUser.ReceiveNotifications =  reNotifications;

        if (ModelState.IsValid)
        {
            db.AdminUsers.Add(adminUser);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.AdminID = new SelectList(db.AdminLogins, "AdminID", "AdminID", adminUser.AdminID);
        ViewBag.RoleID = new SelectList(db.Roles, "RoleID", "RoleName", adminUser.RoleID);
        return View(adminUser);
    }

此外,在上述解决方案之前可以尝试的另一种方法是使用以下代码在模型构造函数中为adminUser.ReceiveNotifications属性定义默认值。 如果您采用这种方法,则不要对标记或Create的操作方法进行任何更改。

 public AdminUser()
        {
            this.Departments = new HashSet<Department>();
            this.Districts = new HashSet<District>();
            this.Divisions = new HashSet<Division>();
            this.Regions = new HashSet<Region>();
            this.Zones = new HashSet<Zone>();
            this.Locations = new HashSet<Location>();
           //add default value for ReceiveNotifications
            this.ReceiveNotifications = false;
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM