user3053007
user3053007

Reputation: 9

saving data from mvc to a database

Hi there everyone I have a Mvc and i am trying to register a user to a sql sever express database using localdb this is the error i am getting " An exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: One or more validation errors were detected during model generation:

AfterCareWebsite.Patient: : EntityType 'Patient' has no key defined. Define the key for this EntityType.

Patient: EntityType: EntitySet 'Patient' is based on type 'Patient' that has no keys defined."

The view

Registration

 @Html.ValidationSummary(true)

 @using (Html.BeginForm())
 {
     @Html.LabelFor(u => u.Email)<br/>
     @Html.TextBoxFor(u => u.Email)<br/>
     @Html.LabelFor(u => u.Password)<br>
     @Html.TextBoxFor(u => u.Password)<br/>
     @Html.LabelFor(u => u.F_Name)<br/>
     @Html.TextBoxFor(u => u.F_Name)<br/>
     @Html.LabelFor(u => u.L_Name)<br/>
     @Html.TextBoxFor(u => u.L_Name)<br/>
     @Html.LabelFor(u => u.Address_Line_1)<br/>
     @Html.TextBoxFor(u => u.Address_Line_1)<br/>

The Controller

 public ActionResult Registration ()    {   return View() }

[HttpPost]
    public ActionResult Registration(Patient model)
    {
        if (ModelState.IsValid)
        {
            using (var db = new MainDbContext())
            {
                var encryptedPassword = CustomEncrypt.Encrypt(model.Password); /*encrypting our password  CustomLibrary*/


              //replaced with below line var Patient = db.Patient.Create();

               var patient = new Patient();
                patient.Email = model.Email;
                patient.Password = encryptedPassword;  
                patient.F_Name = model.F_Name;
                patient.L_Name = model.L_Name;
                patient.Address_Line_1 = model.Address_Line_1;
                db.Patient.Add(patient);  <--- error highlights this line

                      db.SaveChanges();
                 }
            }
        else
        {
            ModelState.AddModelError("","Error with one or more fields,Please check fields");
        }
        return View();
    }

The error highlights this line
var Patient = db.Patient.Create();

Here is the model

       public class Patient
{
    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    //[HiddenInput(DisplayValue =false)]
    //public string ReturnUrl { get; set; }

    public string F_Name{ get; set; }
    public string L_Name { get; set; }

    public string Address_Line_1 { get; set; }
}

Here is a link to an image of the table i am trying to save it to in sql server https://i.sstatic.net/zWjiC.jpg

Upvotes: 0

Views: 1678

Answers (2)

Marcus Vinicius Pompeu
Marcus Vinicius Pompeu

Reputation: 1261

[Editing - I did not see the picture showing the table]

First of all

You WILL bump into more complex problems right after you solve this one, minutes after :-(

I sugest you read a good book on MVC and EF before going back to coding.

Or try one of the thousands tutorials available on the Net, or even from the start page of Visual Studio.

And... your problem is EntityFramework related, not a MVC one.

The solution

You have to make the key explicit at the model code (I assume it is a Identity one):

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

That's it. Your code will succesfully INSERT one patient.

BUT, it will not work for UPDATING, since your controller does not provide an action expecting and Id...

Upvotes: 2

Ahmet Remzi EKMEKCI
Ahmet Remzi EKMEKCI

Reputation: 384

Make sure your id field is auto increment enabled and just change the line that gives the error, like this:

var patient = new Patient();

give a new instance to your patient object and change your variable name.

Upvotes: 1

Related Questions