0

In this project i was trying a Entity Framework Code First Apporach

Table 'Employee'

Id           int               NOT NULL
FirstName    nvarchar(50)      NOT NULL
LastName     nvarchar(50)      NOT NULL
MiddleName   nvarchar(50)      NULL
Address      nvarchar(300)     NULL
Salary       decimal(16,2)     NULL
Email        nvarchar(50)      NULL

It's Perfectly done. Then I Added Entity Framework, Added A EmployeeController. Two Action Method Index & Create with their corresponding Views. Are were so far perfect.

![enter image description here][1] ![enter image description here][2]

Then I Did the following for Employee Add:

    [HttpGet]
    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Employee emp)
    {
        
            if (ModelState.IsValid)
            {
                db.Employees.Add(emp);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(emp);

        
    }

When I Fill the Create View and Submit It's throwing a DbEntityValidationException

![enter image description here][3]

DbEntityValidationException was unhandled by user code

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.

My Database Table is not updating too, now row created there.

Model definition

public partial class Employee
{
  public int Id { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string MiddleName { get; set; }
  public string Address { get; set; }
  public Nullable<decimal> Salary { get; set; }
  public string Email { get; set; }
} 
Community
  • 1
  • 1

2 Answers2

0

taken from here

add this code to your post method, it should help to understand errors you get in output window

[HttpPost]
public ActionResult Create(Employee emp)
{
     try
     {
         if (ModelState.IsValid)
         {
             db.Employees.Add(emp);
             db.SaveChanges();
             return RedirectToAction("Index");
         }
         return View(emp);     
     }
     catch (DbEntityValidationException e)
     {
         foreach (var eve in e.EntityValidationErrors)
         {
              System.Diagnostics.Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
              eve.Entry.Entity.GetType().Name, eve.Entry.State);
              foreach (var ve in eve.ValidationErrors)
              {
                   System.Diagnostics.Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage);
              }
         }
         throw;
     }
}
Community
  • 1
  • 1
aleha_84
  • 8,309
  • 2
  • 38
  • 46
  • sir, the bug remains same, my emp oject is getting values that i submit in the Create View but the update is not reflecting in the Database that's the issue. How would i fix ?? – KH Arif Ahmaad Oct 23 '14 at 10:23
  • @KHArifAhmaad in debug mode did DbEntityValidationException exception catched? What was written in output window? – aleha_84 Oct 23 '14 at 11:11
0

I hate that I cant comment yet, would have been easier to resolve.

Anyway, What I would do when adding a record is, bind the fields and create an instance of the model before saving. This also allows you to use, the much advised, ViewModels.

Change your action to this

[HttpPost]
public ActionResult Create([Bind(Include = "FirstName,LastName,MiddleName,Address,Salary,Email")]Employee u)
{

        if (ModelState.IsValid)
        {
            Employee emp = new Employee
            {
                FirstName = u.FirstName,
                LastName = u.LastName,
                MiddleName = u.MiddleName,
                Address = u.Address,
                Salary = u.Salary,
                Email = u.Email
            };
            db.Employees.Add(emp);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(emp);
}

I didnt include a value for the Id Field as I assume this would be DB generated. If not, then Id would need to be included in Bind and you would need to add code to populate Id with in the initialization of Employee emp

In the event that Id is not DB generated, since I see your Id field is not nullable. To test whether this action code will work, you can do this:

Employee emp = new Employee
            {
                Id = 1,
                FirstName = u.FirstName,
                LastName = u.LastName,
                MiddleName = u.MiddleName,
                Address = u.Address,
                Salary = u.Salary,
                Email = u.Email
            };

1 last thing, to make your Id field DB generated, do this in your T-Sql code

Id           int         IDENTITY(1,1)      NOT NULL    PRIMARY KEY

Hope this sorts it out, or atleast is a first step.

AbdulG
  • 720
  • 5
  • 16