实体类型User不是当前上下文的模型的一部分

时间:2014-09-17 11:03:09

标签: c# asp.net-mvc database entity-framework

我正在使用实体框架数据库。但是当我运行我的应用程序时,我得到了一个名为&#34的异常;类型为#System; InvalidOperationException'发生在EntityFramework.dll中但未在用户代码中处理。实体类型User不是当前上下文的模型的一部分"。

我在context.Users.Add(df);中的LoginController部分得到了错误。

我的实体数据库代码如下所示: 型号:User.cs

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

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

    public partial class User
    {
        public int Id { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string Email { get; set; }
        public string abc { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCRegistrationAndLogin.Models;
using System.Security.Cryptography;
using System.Web.Security;

namespace MVCRegistrationAndLogin.Controllers
{
    public class LoginController : Controller
    {
        // GET: Login
        public ActionResult Index()
        {
            using (var db = new MyDbModelEntities())
            {
                return View(db.Users.ToList());
            }
        }

        public ActionResult UserLogin()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UserLogin(string username, string password)
        {
            using (MyDbModelEntities context = new MyDbModelEntities())
            {
                var user = from u in context.Users
                           where u.UserName == username
                           select u;

                if (user.ToList().Count == 1)
                {
                    if (user.First().Password == CreatePasswordHash(password, user.First().abc))
                    {
                        Session["logged"] = user.First().UserName;
                        return RedirectToAction("ShowProducts", "Products");
                    }
                }
            }
            ModelState.AddModelError("_loginError", "Error in username and password");
            if (!ModelState.IsValid)
                return View();

            return RedirectToAction("UserLogin", "Login");
        }

        private static string CreateSalt()
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] byteArr = new byte[64];
            rng.GetBytes(byteArr);

            return Convert.ToBase64String(byteArr);
        }

        private static string CreatePasswordHash(string password, string aa)
        {
            string passwrodSalt = String.Concat(password, aa);
            string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(passwrodSalt, "sha1");
            return hashedPwd;
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(User df)
        {
            try
            {
                using (var context = new MyDbModelEntities())
                {
                    df.abc = CreateSalt();
                    df.Password = CreatePasswordHash(df.Password, df.abc);
                    **context.Users.Add(df);**
                    context.SaveChanges();

                    return RedirectToAction("Index", "Home");
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException e)
            {
                var outputLines = new List<string>();
                foreach (var eve in e.EntityValidationErrors)
                {
                    outputLines.Add(string.Format(
                        "{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
                        DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
                    foreach (var ve in eve.ValidationErrors)
                    {
                        outputLines.Add(string.Format(
                            "- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage));
                    }
                }
                //Write to file
                System.IO.File.AppendAllLines(@"c:\temp\tulsi_errors.txt", outputLines);

                // Showing it on screen
                throw new Exception(string.Join(",", outputLines.ToArray()));

            }
        }
    }
}

视图:

Register.cshtml

&#13;
&#13;
@model MVCRegistrationAndLogin.Models.User

@{
    ViewBag.Title = "Register";
}

<h2>Register</h2>


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


    <div class="editor-label">
        @Html.LabelFor(model => model.LastName)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)
    </div>


    <div class="editor-label">
        @Html.LabelFor(model => model.FirstName)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.UserName)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model => model.UserName)
        @Html.ValidationMessageFor(model => model.UserName)
    </div>


    <div class="editor-label">
        @Html.LabelFor(model => model.Password)
    </div>
    <div class="editor-field">
        @Html.PasswordFor(model => model.Password)
        @Html.ValidationMessageFor(model => model.Password)
    </div>


    <div class="editor-label">
        @Html.LabelFor(model => model.Email)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model => model.Email)
        @Html.ValidationMessageFor(model => model.Email)
    </div>


    <div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </div>
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
}
&#13;
&#13;
&#13;

UserLogin.cshtml

&#13;
&#13;
@model MVCRegistrationAndLogin.Models.User

@{
    ViewBag.Title = "UserLogin";
}

<h2>UserLogin</h2>

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true, "Login failed due to wrong credentials!!!")
    @Html.AntiForgeryToken()

    <div class="editor-label">
        @Html.LabelFor(model => model.UserName)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model => model.UserName)
        @Html.ValidationMessageFor(model => model.UserName)
    </div>


    <div class="editor-label">
        @Html.LabelFor(model => model.Password)
    </div>
    <div class="editor-field">
        @Html.PasswordFor(model => model.Password)
        @Html.ValidationMessageFor(model => model.Password)
    </div>


    <div>
        <p>
            <input type="submit" value="Login" />
        </p>
    </div>
    <div>
        @Html.ActionLink("New Registration", "Register")
    </div>
}
&#13;
&#13;
&#13;

我该如何解决这个问题?

0 个答案:

没有答案