1

I’ve modified this ContosoUniversity tutorial: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application and now I’m trying to use AutoMapper to map object-to-object.

Here’s my ModelView:

public class InstructorIndexData
{
    public IEnumerable<Instructor> Instructors { get; set; }
    public IEnumerable<Course> Courses { get; set; }
    public IEnumerable<Enrollment> Enrollments { get; set; }
    public IEnumerable<Student> Students { get; set; }
    public IEnumerable<Assignment> Assignments { get; set; }
}

Here’s the view

@model SchoolIn.ViewModels.InstructorIndexData

@using SchoolIn.Models
@{ViewBag.Title = "Index";}


@using (Html.BeginForm("ClassAttendance", "Attendance", 
    new { currentDate = day, id = @ViewBag.ID, 
        teacher = HttpContext.Current.Session["sTeacher"], 
        courseID = HttpContext.Current.Session["sCourseID"] }, FormMethod.Post))

{
    var wekdys = new Enrollment(); @*had too create this to have access to the dropdownList*@
    @Html.DropDownList("weekDays", wekdys.WeekDays.Select(s => 
        new SelectListItem { Text = s.ToString(), Value = s.ToString() }))

    @Html.ValidationSummary(true)
    <p></p>
    <Input Type ="submit" Value="ClassAttendance"/>
    <p>@Html.ActionLink("Create Todays Attendance", "Create")</p>
    <p>@Html.ActionLink("Create New", "Create")</p>
    <h3>Students Enrolled in @ViewBag.teacherName's @ViewBag.courseTitle Course</h3>  
    <table>  
        <tr>  
            <th>View Student Report</th> 
            <th>First Name</th>  
            <th>Last Name</th> 
            <th>Grade</th>  
            <th>Attendance Code</th>  
            <th>Class Day</th> 
        </tr>  
        @foreach (var item in Model.Enrollments)
        {  
        <tr>  
            <td>  
                @Html.ActionLink("Report", "UpdateAttendance", "Attendance", 
                    new { 
                        grade=item.Grade, 
                        studentFirstName = item.Student.FirstMidName, 
                        studentLastName = item.Student.LastName, 
                        courseTitle = item.Course.Title, 
                        teacher = @ViewBag.teacherName }, null)
            </td> 
            <td>@Html.EditorFor(modelItem=>item.Student.FirstMidName)</td>  
            <td>@Html.EditorFor(modelItem=>item.Student.LastName)</td> 
            <td>@Html.EditorFor(modelItem =>item.Grade)</td>
            <td>@Html.DropDownList("attendanceCode", item.attendanceCode.Select(s => 
                 new SelectListItem { Text = s.ToString(), Value = s.ToString() }))
                @*Html.EditorFor(modelItem =>item.attendanceCode)*/*@
            </td>  
            <td>@Html.EditorFor(modelItem=>item.classDays)</td>
        </tr>  
        }  
    </table>  
}

Here’s the method in my controller that I’m having problems with. I’m trying to use this example: http://chriscurrie.co.uk/blog/2011/09/coding/net/mvc/use-automapper-to-map-viewmodels-to-entities-mvc3-and-razor/

public class AttendanceController : Controller
{
    private SchoolInDB db = new SchoolInDB();
}

code here…

[HttpPost]
public ActionResult ClassAttendance(InstructorIndexData viewModel)
{


    if (ModelState.IsValid)
    {

        AutoMapper.Mapper.CreateMap<AttendanceData, Assignment>();
        AutoMapper.Mapper.CreateMap<AttendanceData, Enrollment>();
        AutoMapper.Mapper.CreateMap<AttendanceData, Student>();
        AutoMapper.Mapper.CreateMap<AttendanceData, Instructor>();

        Instructor newInstructor = new Instructor();
        Student newStudent = new Student();
        Assignment newAssignment = new Assignment();
        Enrollment newEnrollment = new Enrollment();

        AutoMapper.Mapper.Map(viewModel, newInstructor );
        AutoMapper.Mapper.Map(viewModel, newStudent);
        AutoMapper.Mapper.Map(viewModel, newEnrollment);
        AutoMapper.Mapper.Map(viewModel, newAssignment);

        db.Assignments.AddObject(newAssignment).;

        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View();
}

When I debug my code stops here ‘AutoMapper.Mapper.Map(viewModel, newInstructor );’ with this error: Missing type map configuration or unsupported mapping.

Mapping types: InstructorIndexData -> Instructor SchoolIn.ViewModels.InstructorIndexData -> SchoolIn.Models.Instructor

Destination path: Instructor

Source value: SchoolIn.ViewModels.InstructorIndexData

Any iI also noticed that in my ActionResult(InstructorIndexData viewModel), viewModel has all null values.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
CloudyKooper
  • 727
  • 3
  • 19
  • 47

1 Answers1

2

According to my understanding the type of viewModel is InstructorIndexData. If so than you need to add configuration:

    AutoMapper.Mapper.CreateMap<InstructorIndexData, Assignment>();
    AutoMapper.Mapper.CreateMap<InstructorIndexData, Enrollment>();
    AutoMapper.Mapper.CreateMap<InstructorIndexData, Student>();
    AutoMapper.Mapper.CreateMap<InstructorIndexData, Instructor>();
k0stya
  • 4,267
  • 32
  • 41
  • Thanks I've changed the CreateMap<> and now the code stops at db.SaveChanges() with the error message The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated. Could this be because the ViewModel has null values here 'ActionResult(InstructorIndexData viewModel'? – CloudyKooper Jul 11 '12 at 21:34
  • Is it a typo "datetime2 data type to a datetime" or you really have the type datetime2? – k0stya Jul 11 '12 at 21:39
  • This issue is not related to the AutoMapper. I would suggest you to ask separate question. Anyway here are few links on the topic: http://stackoverflow.com/questions/1678474/the-conversion-of-a-datetime2-data-type-to-a-datetime-data-type-resulted-in-an-o http://stackoverflow.com/questions/4608734/the-conversion-of-a-datetime2-data-type-to-a-datetime-data-type-resulted-in-an-o – k0stya Jul 11 '12 at 21:49
  • It's not a typo...I'm using datetime in my view but not datetime2 – CloudyKooper Jul 12 '12 at 07:17
  • DateTime is mapped to the datetime2 in the database. – k0stya Jul 12 '12 at 07:54
  • @CloudyKooper Are you still having some issues? – k0stya Jul 17 '12 at 06:02
  • The error "The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value..." occurs when trying to save an uninitialized `DateTime` property to a database created using Entity Framework. (T-SQL column type is [`datetime` with min value of Jan. 1, 1753](http://msdn.microsoft.com/en-us/library/ms187819.aspx) compared to default/min value of `DateTime` of Jan 1, 0001.) To fix it, you must set the property to a non-default value with the range of T-SQL `datetime` or, using EF6, [use T-SQL `datetime2`](http://stackoverflow.com/a/15249018/39396). – Carl G May 27 '13 at 19:28