-2

I have faced a problem which is can't save the record into the database. I have 3 model in one view. I have done the view and getting error about this

An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

here is my view

<div class="container">

<div class="row">

<div class="col-lg-12 management-title">
<h1>Create New Invoice</h1>
</div>

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

<form>

<div class="form-group">
@Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyID, "CompanyID",new { @Name="CompanyID"})
@Html.DropDownList("CompanyID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.CompanyID , "", new { @class = "text-danger" })
</div>

@Html.ValidationSummary(true, "", new { @class = "text-danger" })                 

<div class="panel-group">
<div class="panel panel-default">
    <div class="panel-heading">
        <h4 class="panel-title">
            <a data-toggle="collapse" href="#bill_to_company">Company Details</a>
        </h4>
    </div>
    <div id="bill_to_company" class="panel-collapse collapse in wrapper-company-details">

        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">

            <div class="form-group">
                @Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyName)
                @Html.TextBoxFor(model => model.PurchaseInvoiceTable.CompanyName, new { @class = "form-control" })
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyAddress)
                @Html.TextAreaFor(model => model.PurchaseInvoiceTable.CompanyAddress, new { @class = "form-control golbal_textarea" })
            </div>

        </div>

        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">

            <div class="form-group">
                @Html.LabelFor(model => model.PurchaseInvoiceTable.startdate)
                @Html.TextBoxFor(model => model.PurchaseInvoiceTable.startdate, new { @class = "form-control", @Value = @DateTime.Now.ToString() })
            </div>

            <div class="form-group">

            </div>

        </div>

    </div>
</div>
</div>

<h2>Product List</h2>

<div class="panel-group">
<div class="panel panel-default">
    <div class="panel-heading">
        <h4 class="panel-title">
            <a data-toggle="collapse" href="#product_list">Product List</a>
        </h4>
    </div>
    <div id="product_list" class="panel-collapse collapse in input_fields_wrap">
        <div class="panel-group" id="accordion">
            <div class="panel panel-default">

                <div class="panel panel-default product_wrapper">

                    <div class="panel-heading">

                        <h4 class="panel-title">

                            <a data-toggle="collapse" data-parent="#accordion" href="#product' + x + '">Product</a>

                        </h4>

                    </div>

                    <div id="product'+x+'" class="panel-collapse collapse in">

                        <div class="panel-group">

                            <div class="panel panel-default">


                                <div class="col-lg-12">


                                    <div class="col-lg-3">

                                        <label>Product</label>
                                        @Html.TextAreaFor(model => model.PurchaseInvoiceDetailsTable.Product)

                                    </div>

                                    <div class="col-lg-6">

                                        <label>Description</label>
                                        @Html.TextAreaFor(model => model.PurchaseInvoiceDetailsTable.ProductDescription)

                                    </div>

                                    '<div class="col-lg-2 form-group">

                                        <label>Price</label>
                                        @Html.TextBoxFor(model => model.PurchaseInvoiceDetailsTable.Price)

                                    </div>


                                </div>


                            </div>

                        </div>


                    </div>
                   <a href="#" class="remove_field btn btn-danger pull-right">cancel</a>

                </div>                                      

            </div>
        </div>

    </div>
</div>
</div>

<button class="add_field_button btn btn-primary pull-right">Add More Fields</button>

<div class="wrapper-company-details">

    <div class="form-group">
        @Html.LabelFor(model => model.PurchaseInvoiceTable.Remark)
        @Html.TextAreaFor(model => model.PurchaseInvoiceTable.Remark, new { @class = "form-control", @style = "resize:none;" })
        @Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Remark, "", new { @class = "text-danger" })
    </div>

    <h1>Payment Term Area</h1>

    <div class="panel-group">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h4 class="panel-title">
                    <a data-toggle="collapse" href="#payment_term_collapse">Payment Term</a>
                </h4>
            </div>

            <div id="payment_term_collapse" class="payment_term_area panel-collapse collapse in">

                <table class="table table-bordered">

                    <tr style="background-color:black; color:white;">

                        <th style="width:70%;">
                            <input type="text" class="form-control" id="payment_term" placeholder="Type how many terms client want" />
                        </th>


                        <th style="width:30%;">
                            <button class="btn btn-default" id="add_payment_terms">Add</button>
                        </th>

                    </tr>

                </table>

                <table class="table table-bordered">

                    <tr style="background-color:black; color:white;">

                        <th style="width:70%;">
                            Payment Term
                        </th>


                        <th style="width:30%;">
                            Amount
                        </th>

                    </tr>


                    <tr style="background-color:black; color:white;">

                        <th style="text-align:right;">
                            Discount
                        </th>

                        <th>
                            @Html.TextBoxFor(model => model.PurchaseInvoiceTable.Discount, new { @class = "form-control discount price_textbox", @id = "discount", @Value = "0" })
                        </th>

                    </tr>

                    <tr style="background-color:black; color:white;">

                        <th style="text-align:right;">
                            Total
                        </th>

                        <th>
                            @Html.TextBoxFor(model => model.PurchaseInvoiceTable.Subtotal, new { @class = "form-control price_textbox total", @id = "totval", @Value = "0" })
                        </th>

                    </tr>
                </table>

                <div id="payment_term_area">

                    <h2>Payment Terms</h2>

                    <div class="payment_term_wrapper" style="padding:0; margin:0;">

                        <table class="table table-bordered" style="width:95%;">


                            <tr style="background-color:black; color:white;" class="payment_term_wrapper">


                                <th style="width:70%;">

                                    <input class="pull-right payment_terms_label_input" style="background-color:black; color:white;"></input>

                                </th>

                                <th style="width:30%;">

                                    @Html.TextBoxFor(model => model.PaymentTerm.Amount)

                                </th>

                            </tr>

                            <a href="#" class="remove_field btn btn-danger pull-right">X</a>

                        </table>

                    </div>

                </div>

                <table class="table table-bordered">
                    <tr style="background-color:black; color:white;">

                        <th style="text-align:right; width:70%;">
                            Last Payment
                        </th>

                        <th style="width:30%;">
                            @Html.TextBoxFor(model => model.PurchaseInvoiceTable.Total, new { @class = "form-control price_textbox", @id = "lastpayment", @Value = "0" })
                        </th>

                    </tr>
                </table>

            </div>
        </div>
    </div>

</div>

<div class="col-lg-12">

</div>

<div class="col-lg-12">

    <div class="form-group">
        @Html.LabelFor(model => model.PurchaseInvoiceTable.Category, "Category")
        @Html.DropDownList("Category", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Category, "", new { @class = "text-danger" })
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.PurchaseInvoiceTable.Method)

        @Html.DropDownListFor(model => model.PurchaseInvoiceTable.Method, new List<SelectListItem>
{
new SelectListItem() {Text = "Cash", Value="Cash"},
new SelectListItem() {Text = "Cheque", Value="Cheque"},
new SelectListItem() {Text = "Bank Transfer", Value="BankTransfer"}
}, new { @class = "form-control" })

        @Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Method, "", new { @class = "text-danger" })
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.PurchaseInvoiceTable.PaymentTerm, "PaymentTerm", htmlAttributes: new { @class = "control-label col-md-2" })
        @Html.DropDownListFor(model => model.PurchaseInvoiceTable.PaymentTerm, new List<SelectListItem>
{
new SelectListItem() {Text = "1", Value="1"},
new SelectListItem() {Text = "2", Value="2"},
new SelectListItem() {Text = "3", Value="3"}
}, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.PaymentTerm, "", new { @class = "text-danger" })
    </div>

    <div class="form-group">
        @Html.HiddenFor(model => model.PurchaseInvoiceTable.Status, new { @class = "form-control", @Value = "Active" })
        @Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.Status, new { @class = "form-control", @Value = "Active" })
        @Html.HiddenFor(model => model.PaymentTerm.Status, new { @class = "form-control", @Value = "Active" })
    </div>

    <div class="form-group">
        @Html.HiddenFor(model => model.PurchaseInvoiceTable.first_created, new { @class = "form-control", @Value = @DateTime.Now.ToString() })
        @Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.first_created, new { @class = "form-control", @Value = @DateTime.Now.ToString() })
        @Html.HiddenFor(model => model.PaymentTerm.first_created, new { @class = "form-control", @Value = @DateTime.Now.ToString() })
    </div>

    <div class="form-group">
        @Html.HiddenFor(model => model.PurchaseInvoiceTable.first_created_by, new { @class = "form-control", @Value = @Session["Username"].ToString() })
        @Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.first_created_by, new { @class = "form-control", @Value = @Session["Username"].ToString() })
        @Html.HiddenFor(model => model.PaymentTerm.first_created_by, new { @class = "form-control", @Value = @Session["Username"].ToString() })
    </div>

    <div class="form-group">
        @Html.HiddenFor(model => model.PurchaseInvoiceTable.last_updated, new { @class = "form-control", @Value = @DateTime.Now.ToString() })
        @Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.last_updated, new { @class = "form-control", @Value = @DateTime.Now.ToString() })
        @Html.HiddenFor(model => model.PaymentTerm.last_updated, new { @class = "form-control", @Value = @DateTime.Now.ToString() })
    </div>

    <div class="form-group">
        @Html.HiddenFor(model => model.PurchaseInvoiceTable.last_updated_by, new { @class = "form-control", @Value = @Session["Username"].ToString() })
        @Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.last_updated_by, new { @class = "form-control", @Value = @Session["Username"].ToString() })
        @Html.HiddenFor(model => model.PaymentTerm.last_updated_by, new { @class = "form-control", @Value = @Session["Username"].ToString() })
    </div>

    <div class="form-group">
        <div>
            <input type="submit" value="Create" class="btn btn-primary pull-right" />
            @Html.ActionLink("Back", "Index", null, new { @class = "btn btn-small btn-danger pull-right", @style = "margin-right:2%;" })
        </div>
    </div>
</div>
</form>
}
</div>
</div>

here is my controller

 public ActionResult Create()
    {
        ViewBag.CompanyID = new SelectList(db.SupplierTables, "SupplierID", "SupplierID");
        ViewBag.Product = new SelectList(db.ProductTables, "ProductID", "ProductID");
        ViewBag.Category = new SelectList(db.CategoryTables, "CategoryID", "CategoryID");
        ViewBag.PaymentTerm = new SelectList(db.PaymentTerms, "TermID", "TermID");
        return View();
    }

    [HttpPost]
    public ActionResult Create([Bind(Include = "PurchaseInvoiceTable,PurchaseInvoiceDetailsTable,PaymentTerm")]InvoiceWrapper model)            
    {
        if (ModelState.IsValid)
        {

                db.PurchaseInvoiceTables.Add(model.PurchaseInvoiceTable);
                db.PurchaseInvoiceDetailsTables.Add(model.PurchaseInvoiceDetailsTable);
                db.PaymentTerms.Add(model.PaymentTerm);
                db.SaveChanges();

            //model.PurchaseInvoiceTable.PurchaseInvoiceID = model.PurchaseInvoiceDetailsTable.InvoiceID = model.PaymentTerm.InvoiceID;                   

            return RedirectToAction("Index");
        }

        ViewBag.CompanyID = new SelectList(db.SupplierTables, "SupplierID", "SupplierID");
        ViewBag.Product = new SelectList(db.ProductTables, "ProductID", "ProductID");
        ViewBag.Category = new SelectList(db.CategoryTables, "CategoryID", "CategoryID");
        ViewBag.PaymentTerm = new SelectList(db.PaymentTerms, "TermID", "TermID");
        return View(model);
           
        
    }
Community
  • 1
  • 1
nonstop328
  • 629
  • 1
  • 6
  • 17
  • Why are you calling `db.PurchaseInvoiceDetailsTables.Add(model.PurchaseInvoiceDetailsTable);` and `db.PaymentTerms.Add(model.PaymentTerm);` twice. And what does _See 'EntityValidationErrors' property for more details_ tell you –  Nov 29 '16 at 04:52
  • 1
    And why in the world do you have all those hidden inputs. Use view models. –  Nov 29 '16 at 04:53
  • twice is i doing testing didn't delete== , hidden input is for when i create it will auto insert wont let user type the hidden value – nonstop328 Nov 29 '16 at 04:55
  • Use view models and get rid of all those hidden inputs. And again - _what does See 'EntityValidationErrors' property for more details_ tell you –  Nov 29 '16 at 04:56
  • @StephenMuecke it is view more details? – nonstop328 Nov 29 '16 at 08:34
  • You need to inspect the errors to see what the issue is (we cannot see them). And best guess is that `PurchaseInvoiceDetailsTables` has a relationship to the ID of `PurchaseInvoiceTable` (and you have not set the value for the FK. –  Nov 29 '16 at 08:36
  • @StephenMuecke How do i manage to save the FK? my primary `PurchaseInvoiceTable - PurchaseInvoiceID` have link with `PurchaseInvoiceDetailsTables - InvoiceID` and `PaymentTerms-InvoiceID`, i get null value when i save to db. What should i do? – nonstop328 Dec 07 '16 at 07:34
  • Call `db.SaveChanges();` after `db.PurchaseInvoiceTables.Add(model.PurchaseInvoiceTable);`, then set the FK property of `PurchaseInvoiceDetailsTable` based on the ID of `PurchaseInvoiceTable` –  Dec 07 '16 at 07:36
  • @StephenMuecke thx for you help!! it works. But i have 1 more question is how do i manage to save multiple value from dynamic add textbox from javascript? – nonstop328 Dec 07 '16 at 08:15
  • Ask a new question :) –  Dec 07 '16 at 08:16

1 Answers1

0

The exception you are getting means that one or more of the entities properties that you are trying to save is not valid. e.g. The column is defined as not null and the property you are trying to save is null.

In order to see the validation errors you can use this:

catch (DbEntityValidationException dbEx)
{
    foreach (var validationErrors in dbEx.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            Trace.TraceInformation("Property: {0} Error: {1}", 
                                    validationError.PropertyName, 
                                    validationError.ErrorMessage);
        }
    }
}

credits

Community
  • 1
  • 1
Rayno Jacobs
  • 126
  • 3