3 Replies - 18527 Views - Last Post: 29 March 2013 - 10:32 AM

#1 Luke24  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 07-January 13

Saving to Database

Posted 15 February 2013 - 08:10 AM

Hey

Trying to get my head around MVC, just could someone let me know if im doing this wrong

I created a database within MSSQL, I then generated that database to ADO.NET Entity within my application

There was just one table "Students"

So now I have two classes Student(The Entity Class) and StudentModel(The class I use for validation for Views)

I have a StudentRepositry class, which saves to the database perfectly fine, using the context.Students.Add(Student)

Now within my controller and view, im passing the StudentModel but when I save I need to save it as a Student. Should I be converting StudentModel to a Student before saving to the database, or am I using MVC wrong?

Is This A Good Question/Topic? 0
  • +

Replies To: Saving to Database

#2 HopelessDev  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 136
  • Joined: 10-August 12

Re: Saving to Database

Posted 16 February 2013 - 05:08 AM

If your StudentModel has the same properties as your Student entity class, you could map their property values.

var student = new Student 
{
  StudentId = studentModel.ID,
  Name = studentModel.Name,
  Address = studentModel.Address
}

context.Students.Add(student);
context.SaveChanges();


Was This Post Helpful? 0
  • +
  • -

#3 Nakor  Icon User is offline

  • Professional Lurker
  • member icon

Reputation: 444
  • View blog
  • Posts: 1,492
  • Joined: 28-April 09

Re: Saving to Database

Posted 16 February 2013 - 03:21 PM

This is where tools like AutoMapper come in very handy. You can set it up to automatically map your models to your entities.

Another option is to create a extension to map your model to your entity class and vice versa. Since you are only dealing with one mapping this is fairly simple. If you had 20 or 30 classes to deal with then I'd urge you more strongly to look into the AutoMapper library I mentioned above.

Here's a quick example of creating the extension

public static class MapExtensions
{
  // Creating new instances of the class you're mapping to  
  public static Student ConvertToStudent(this StudentModel model)
  {
    Student student = new Student();
    student.StudentID = model.StudentID;
    student.FirstName = model.FirstName;
    student.LastName = model.LastName;

    return student;
  }

  public static StudentModel ConvertToStudentModel(this Student student)
  {
    StudentModel model = new StudentModel();
    model.StudentID = student.StudentID;
    model.FirstName = student.FirstName;
    model.LastName = student.LastName;

    return model;
  }

  // Updating an existing student, you don't really need
  // a function to update a StudentModel since it is not 
  // the object connected to your database
  public static Student ConvertToStudent(this StudentModel model, Student student)
  {
    student.StudentID = model.StudentID;
    student.FirstName = model.FirstName;
    student.LastName = model.LastName;

    return student;
  }
}



And an example of how that might be used
public ActionResult GetStudent(int id)
{
  Student student = context.Students.Find(id);
  StudentModel model = student.ConvertToStudentModel();

  return View(model);
}

public ActionResult Create(StudentModel model)
{
  Student student = model.ConvertToStudent();
  context.Students.Add(student);
  context.SaveChanges();  

  return View();
}

public ActionResult Update(StudentModel model)
{
  Student student = context.Students.Find(model.StudentID);

  // Here you pass in the existing student so it can be udpated
  student = model.ConvertToStudentModel(student);  

  context.SaveChanges();  

  return View();
}



This code is from memory and wasn't tested so it might need some tweaking, but hopefully it will help you get started.

This post has been edited by Nakor: 16 February 2013 - 03:23 PM

Was This Post Helpful? 0
  • +
  • -

#4 BattlFrog  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 72
  • Joined: 09-April 12

Re: Saving to Database

Posted 29 March 2013 - 10:32 AM

ANother option is a partial student class, which would extend the class automaticlly made by EF when you make the edmx file. You put the validation stuff in the partial and save to the original Student class. Supposing a student class like:

STUDENT (id, Fname, Lname, StudentNumber, DOB)

partial class would be:


using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Web.Mvc;

namespace EligibityForm.Models
{
    [MetadataType(typeof (PersonMetadata))]
    public partial class Student
    {

    }

    public class StudentModel
    {
        [Required (ErrorMessage="First Name Required")]        
        [DisplayName ("First Name")]
        [RegularExpression(@"[a-zA-Z]+('[a-zA-Z])?[a-zA-Z]*", ErrorMessage = "First name may only contain letters")]
        [StringLength(20)]
        public string FirstName { get; set; }
        
        [Required (ErrorMessage="Last Name Required")]
        [DisplayName("Last Name")]
        [RegularExpression(@"[a-zA-Z\s]+('[a-zA-Z])?[a-zA-Z]*", ErrorMessage = "Last name may only contain letters")]
        [StringLength(50)]
        public string LastName { get; set; }

        etc...





Then in the view, assuming you had a form for someone to register as a new student, you would have stuff like:

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





which when submitted, shoots it to the controller where you do:


[HttpPost]
    public ActionResult SaveStudent(Student model)
    {
      try
      {
        using (var db = new StudentEntities())
        {
          db.Student.Add(model);
          db.SaveChanges();
        }
        return RedirectToAction("Index");
      }
      catch
      {
        return View();
      }
    }





Atleast, that's how i do it :online2long:

This post has been edited by BattlFrog: 29 March 2013 - 10:32 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1