为什么调用的SaveChanges()抛出错误"未将对象引用设置到对象的实例&QUOT。 [英] why call to saveChanges() throws error "Object reference not set to an instance of an object."

查看:215
本文介绍了为什么调用的SaveChanges()抛出错误"未将对象引用设置到对象的实例&QUOT。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code的观点:

i have the following code for view:

@model test1.Models.CustomerVM

@{
    ViewBag.Title = "Create";
}
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />
<h2>Create</h2>

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

    <fieldset>
        <legend>Customer</legend>

        @Html.HiddenFor(model=>model.UserId)
        @Html.HiddenFor(model=>model.Id)

        <div class="editor-label">
            @Html.LabelFor(model => model.User)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.User)
            @Html.ValidationMessageFor(model => model.User)
        </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.ConfirmPassword)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(model => model.ConfirmPassword)
            @Html.ValidationMessageFor(model => model.ConfirmPassword)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.NameTitle)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.NameTitle, Model.NameTitleColl)
            @Html.ValidationMessageFor(model => model.NameTitle)
        </div>

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

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

        <div class="editor-label">
            @Html.LabelFor(model => model.Gender)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.Gender, Model.GenderColl)
            @Html.ValidationMessageFor(model => model.Gender)
        </div>

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

        @* contacts *@
             <div class="editor-label">
            @Html.LabelFor(model => model.AddressL1)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.AddressL1)
            @Html.ValidationMessageFor(model => model.AddressL1)
        </div>

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

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

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

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

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

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

@section Scripts {

    <script src="~/Scripts/jquery-2.1.4.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.11.4.min.js"></script>

    @Scripts.Render("~/bundles/jqueryval")

    <script>
        $(document).ready(function () {
            $('#DOB').datepicker({
                appendText: 'mm/dd/yyyy',
                showOn: 'both',
                buttonText: 'click me',
                dateFormat: 'mm/dd/yy',
                changeMonth: 'true',
                changeYear: 'true',
                yearRange: '1900:2016'
            });
        });
    </script>

}

视图工作正常,数据显示为它应该是。但是当我点击创建保存记录以下错误抛出:对象引用不设置到对象的实例这是抛出时,它执行线db.SaveChanges();

the view works fine displays data as it should be. but when i click Create to save record the following error throws : Object reference not set to an instance of an object This is thrown when it executes the line db.SaveChanges();

下面是它的保存操作。 注意:虽然认为有更多的领域,但林不保存所有只有我在已经指出的那些创建()将被保存在a.k.a仅mst_users数据将被保存

Here is the action that does the save. Note: though the view has more field but im not saving all only the ones i have stated in Create() will be saved a.k.a only data in mst_users will be saved

    [HttpPost]
    public ActionResult Create(CustomerVM custObject)
    {

            if (ModelState.IsValid)
            {
                mst_users user = new mst_users 
                { 
                    uName=custObject.User, 
                    password=custObject.Password, 
                    dtCreated=DateTime.UtcNow, 
                    isLocked=false
                };

                db.mst_users.Add(user);
                db.SaveChanges();
         }
   }

当我接收数据检查的方法有所有需要的数据执行保存,但有趣的是,当它抛出调试器作为控制到了视图例外并指向 NameTitle 字段。

when i check the receiving data to the method it has all the required data to do the save but funny thing is when it throws the exception the debugger takes the control to the the view and points to the NameTitle field.

Line 44:         </div>
Line 45:         <div class="editor-field">
Line 46:             @Html.DropDownListFor(model => model.NameTitle, Model.NameTitleColl)
Line 47:             @Html.ValidationMessageFor(model => model.NameTitle)
Line 48:         </div>

下面是一个映射到实体类mst_users表

here is the table that maps to Entity class mst_users

 [uName] varchar
 [password] varchar
 [dtCreated] datetime
 [dtUpdated] datetime
 [isLocked] bit

下面是实体类:

在这里输入的形象描述

是视频

下面是空引用错误的视频

推荐答案

正如你指出:

但有趣的是,当它抛出调试器作为控制的视图,并指向NameTitle领域的除外。

问题是不是准确的的SaveChanges(),但是当成功地执行你的动作实际上发生的异常,你同样的创建的观点是再次呈现。这个时候,你的模式 Model.NameTitleColl

The problem is not exactly at SaveChanges(), but the exception actually occurs when your action is successfully executed and your same Create view is rendered again. This time, your Model or Model.NameTitleColl is null.

当您得到调用你的创建操作,必须填充你的 CustomerVM 方法,它返回视图。但要做出POST调用调用你的创建方法,如果你想再次呈现了同样的观点,你必须填写你的 CustomerVM 再次,到了最后,并把它传递给视图。是这样的:

When you make get call to your Create action, you must be populating your CustomerVM method and returning it to view. But after making POST call call to your Create method, if you want to render the same view again, you must populate your CustomerVM again, at the end, and pass it to the view. something like:

[HttpPost]
public ActionResult Create(CustomerVM custObject)
{

        if (ModelState.IsValid)
        {
            mst_users user = new mst_users 
            { 
                uName=custObject.User, 
                password=custObject.Password, 
                dtCreated=DateTime.UtcNow, 
                isLocked=false
            };

            db.mst_users.Add(user);
            db.SaveChanges();
     }

    return View(custObject);
    //or return View(new CustomerVM()) just to make you understand

}

更新: (根据您连接视频)

您只填充用户密码 ConfirmPassword 你的 CustomerVM 模型的领域。而你装饰了你的地址 FNAME 和其他几个属性 * [必填] * 属性。这意味着,它不能是发布时,(为了使模型有效)。否则,你的模型的状态将是无效的。您可以在视频清楚地看到, custObject 包含空所需的值。那么究竟不如预期,您 ModelState.IsValid 会给你的回报。

You are only populating User, Password and ConfirmPassword field of your CustomerVM model. And you have decorated your Address, Fname and several other properties with *[Required]* attribute. Which means, it MUST not be null when posted, (in order to make model valid). Otherwise, your model state would be invalid. You can clearly see in video, custObject contains null for required values. so exactly as expected, you ModelState.IsValid will give you false in return.

更新: (根据您连接第二个视频)
你说得对,你的异常在 db.SaveChanges()行发生。原因为什么你需要调试器,您可以查看以下是在动作片code的:

UPDATE: (based on second video you attached) You are right, your exception occurs at db.SaveChanges() line. The reason for why your debugger takes you to view is following piece of code in your action:

try
{
   ....
   db.SaveChanges();
 }
 catch()
 {
   return View(); // <- this line
 }

所以在技术上,异常发生,而你的程序的控制移动到您的catch块。并执行返回查看()为了处理您的异常,并在视图显示, Model.NameTitleColl 为空。这将引发另一个异常,你实际看到的。然而,你跳过了一部开拓创新的例外。

so technically, exception occurs, and the control of your program is moved to your catch block. and you execute return View() in order to handle your exception and when view is rendered, Model.NameTitleColl is null. This throws another exception, which you actually see. whereas, you have skipped the orignal exception.

原因及解决方法:

从code,我所看到的,你不要在你的行动,这将引发异常一部开拓创新的初始化分贝对象。你在其上执行任何操作之前,请初始化分贝对象。你可以这样做:

From your code, I can see, you do not initialize your db object in your action, which throws the orignal exception. Please initialize the db object before you perform any action on it. You can do something like:

db = new YourDbContextNameHere(); //initialize your db object with your Dbcontext class constructor

然后执行:

db.mst_users.Add(user);
db.SaveChanges();

这将罚款这种方式。

it will work fine this way.

这篇关于为什么调用的SaveChanges()抛出错误&QUOT;未将对象引用设置到对象的实例&QUOT。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆