实体框架:NullReferenceException

时间:2018-12-04 16:12:38

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

下面的Entity Framework数据库优先方法面临问题。

我的模型班:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    namespace LCM_API.Models
    {
        public partial class User
        {
            [Key]
            public int UserId { get; set; }

            [Required]
            [StringLength(500)]
            public string FirstName { get; set; }
            [Required]
            [StringLength(500)]
            public string LastName { get; set; }
            [Required(ErrorMessage = "Required EmailID")]
            [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter Valid Email ID")]
            [StringLength(500)]
            public string Email { get; set; }

            [StringLength(10)]
            public string Phone { get; set; }
            [Required]
            [StringLength(10)]
            public string AccessControl { get; set; }

            [Required(ErrorMessage = "Required Username")]
            [StringLength(10, MinimumLength = 2, ErrorMessage = "Username Must be Minimum 2 Charaters")]
            public string UserName { get; set; }
            [DataType(DataType.Password)]
            [Required(ErrorMessage = "Required Password")]
            [MaxLength(20, ErrorMessage = "Password cannot be Greater than 30 Charaters")]
            [StringLength(21, MinimumLength = 7, ErrorMessage = "Password Must be Minimum 7 Charaters")]
            public string Password { get; set; }
        }
    }

IRegisterUser界面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LCM_API.Models;

namespace LCM_API.Repositry
{
   public interface IRegisterUser
    {
        User Add(User registeruser);
        bool ValidateRegisteredUser(User registeruser);
        bool ValidateUsername(User registeruser);
        int GetLoggedUserID(User registeruser);
    }
}

RegisterUser

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LCM_API.Models;
using System.Data.Entity;

namespace LCM_API.Repositry
{
    public class RegisterUser:IRegisterUser
    {
        private  LCMTestEntities _context ;

        // Users usr = new Users();

        public RegisterUser()
        {
           _context = new LCMTestEntities();
        }

        public User Add(User registeruser)
        {
            try
            {
                _context.RUser.Add(registeruser);
                _context.SaveChanges();
                return registeruser;
            }
            catch(Exception e)
            {
               throw e.InnerException;
            }
        }

        public bool ValidateRegisteredUser(User registeruser)
        {
            var usercount = (from Users in _context.RUser
                             where Users.UserName == registeruser.UserName && Users.Password == registeruser.Password
                             select Users).Count();

            if (usercount > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public  bool ValidateUsername(User registeruser)
        {
            var usercount = (from Users in _context.RUser
                             where Users.UserName == registeruser.UserName
                             select Users).Count();
            if(usercount > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public  int GetLoggedUserID(User registeruser)
        {
            var usercount = (from Users
                             in _context.RUser
                             where Users.UserName == registeruser.UserName && Users.Password == registeruser.Password
                             select Users).Count();
            return usercount;
        }
    }
}

UsersController类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using a=System.Web.Http;
using b=System.Web.Mvc;
using System.Security.Cryptography;
using LCM_API.Models;
using LCM_API.Repositry;
using LCM_API.AES256Encryption;

namespace LCM_API.Controllers
{
    public class UsersController : a.ApiController
    {
        IRegisterUser repository = new RegisterUser();
        private LCMTestEntities ls = new LCMTestEntities();

        // RegisterUser ru = new RegisterUser();
        // public UsersController()
        // {
        //    repositry = new RegisterUser();
        // }
        [a.Route("api/LCM/Create")]
        [a.HttpPost]
        public a.IHttpActionResult Create([a.FromBody]User usrs)
        {
            usrs.Password = EncryptionLibrary.EncryptText(usrs.Password);

            User usr = repository.Add(usrs);

            if (repository.ValidateUsername(usrs))
            {
                return Content(HttpStatusCode.Found, "User is already registered");
            }

            return Ok(usr);
        }

        [a.Route("api/LCM/GetUsers")]
        public a.IHttpActionResult GetAllUsers()
        {
           var lm1= ls.RUser.SqlQuery("Select * from LCMTest.mag123.Users");

           if (lm1 == null)
                return NotFound();

           return Ok(lm1);
        }
    }
}

我的DBContext班:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace LCM_API.Models
{
        using System;
        using System.Data.Entity;
        using System.Data.Entity.Infrastructure;

        public partial class LCMTestEntities : DbContext
        {
            public LCMTestEntities()
                : base("name=LCMTestEntities")
            {
                this.Configuration.LazyLoadingEnabled = true;
                this.Configuration.ProxyCreationEnabled = true;
            }

            public virtual DbSet<AppData> LCMInfo { get; set; }
            public virtual DbSet<User> RUser { get; set; }
            public virtual DbSet<ClientKey> ClientKeys { get; set; }
            public virtual DbSet<TokensManager> TokensManager { get; set; }

            // protected override void OnModelCreating(DbModelBuilder modelBuilder)
            //    {
            //    }
        }
    }

当我尝试使用邮递员发布以下数据

{
    "FirstName": "somename",
        "LastName": "somename",
        "Email": "xyzhab@gmail.com",
        "Phone": "78654321",
        "AccessControl": "Normal",
        "UserName": "xyz123",
        "Password": "hswuhwuddfrtx"
}

我在NullReferenceException上看到一个_context.SaveChanges(),上面写着

{
    "$id": "1",
    "Message": "An error has occurred.",
    "ExceptionMessage": "Object reference not set to an instance of an object.",
    "ExceptionType": "System.NullReferenceException",
    "StackTrace": "   at LCM_API.Repositry.RegisterUser.Add(User registeruser) in C:\\Program Files (x86)\\Microsoft Visual Studio\\Projects\\LCM_API\\LCM_API\\Repositry\\RegisterUser.cs:line 30\r\n   at LCM_API.Controllers.UsersController.Create(User usrs) in C:\\Program Files (x86)\\Microsoft Visual Studio\\Projects\\LCM_API\\LCM_API\\Controllers\\UsersController.cs:line 31\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}

这是格式化的堆栈跟踪:

   at LCM_API.Repositry.RegisterUser.Add(User registeruser) in C:\\Program Files (x86)\\Microsoft Visual Studio\\Projects\\LCM_API\\LCM_API\\Repositry\\RegisterUser.cs:line 30
   at LCM_API.Controllers.UsersController.Create(User usrs) in C:\\Program Files (x86)\\Microsoft Visual Studio\\Projects\\LCM_API\\LCM_API\\Controllers\\UsersController.cs:line 31
   at lambda_method(Closure , Object , Object[] )
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

过去1周来我一直在这个问题上停留,无法继续前进。请有人帮我解决这个问题。

0 个答案:

没有答案