0

Since I have started using DATABASE FIRST approach of entity framework. It's easy to catch on and interesting but there's one thing that puzzles me.

In MVC we usually make view models (models with plus-minus properties so it adheres to the particular view). Fine but while using the EF with DB first approach this seems to be impossible. Because we create one model off a database table and then keeps on using it for insert, update, select or anything.

e.g.

Services model:

namespace ZahidCarWash.Models.EF
{
    using System;
    using System.Collections.Generic;

    public partial class Services
    {
        public short ServiceID { get; set; }
        public string ServiceName { get; set; }
        public Nullable<decimal> ServicePrice { get; set; }
        public Nullable<System.DateTime> EntryDateTime { get; set; }
        public Nullable<bool> IsOwner { get; set; }
        public Nullable<decimal> Commission { get; set; }
    }
}

and then using it in controllers.

        [HttpPost]
        public JsonResult UpdateServices(Services UpdateServicesVM)
        {

            ServicesRepository ServicesRep = new ServicesRepository();

            int i = 0;

            //i = ServicesRep.UpdateServices(UpdateServicesVM, out ReturnStatus, out ReturnMessage);

            ZahidCarWashDBEntities zjdb = new ZahidCarWashDBEntities();
            zjdb.Entry(UpdateServicesVM).State = EntityState.Modified;
            i= zjdb.SaveChanges();

            return Json(new { ReturnMessageJSON = i > 0 ? "Success" : "Error", ReturnStatusJSON = i > 0 ? true : false });

        }

Or

        [HttpPost]
        public JsonResult AddServices(Services AddServicesVM)
        {

            ServicesRepository ServicesRep = new ServicesRepository();

            int i = 0;

            //i = ServicesRep.InsertServices(AddServicesVM, out ReturnStatus, out ReturnMessage);
            ZahidCarWashDBEntities context = new ZahidCarWashDBEntities();

            context.Services.Add(AddServicesVM);

            context.SaveChanges();

            return Json(new { ReturnMessageJSON = ReturnMessage, ReturnStatusJSON = ReturnStatus });

        }

I created other customized models by adding/removing properties but that doesn't sound good. Any decent way to do or EF provides?

azure boy
  • 193
  • 8
  • You should create ViewModels for Views (not for/from Models). There is not much tooling for that, most programmers just write them. The code generation tools (scaffolding) only support direct CRUD, that means your datamodel defines your UI. Not good for most of a good site. – bommelding Jan 08 '19 at 08:49
  • correct but suppose that a view is passing a view model A, but the controller is working on Model B (generated by entity framework), so the parameter should be type A and that's the problem – azure boy Jan 08 '19 at 09:42
  • A controller can work with 0 or more models. It's its job to translate queries into ViewModels and the result into Updates. – bommelding Jan 08 '19 at 09:49
  • didn't get it? ? – azure boy Jan 08 '19 at 09:54
  • Update/Insert a Model B (and maybe a Model C) from a ViewModel A is a normal workflow for MVC. – bommelding Jan 08 '19 at 10:01
  • so for that I would have to inherit Model B from A otherwise it won't know about it properties. – azure boy Jan 08 '19 at 10:19
  • No, absolutely not. – bommelding Jan 08 '19 at 10:23
  • can you write an example just by modifying my code so I better understand what you want to say actually. – azure boy Jan 08 '19 at 10:27
  • also in the answers box so i can accept as an answer. – azure boy Jan 08 '19 at 10:27

1 Answers1

3

You are mixing two things here: Database Entities (Entity Data Model) & View Models which are two different concepts.

  • Data Model: It is a simple class related to specified table from the database and can be used in the code as data model.

  • View Model: Conceptually, it is related to MV* architectural patterns and is used to pass data to/from a view. Keep it related to your UI logic.

To implement these two concepts in an MVC application using Entity Framework, consider the database tables as Data Entities and keep it only to communicate with database. To perform CRUD operations and to pass data to and from a view, use View Models.

Example:

Data Model

namespace ZahidCarWash.Models.EF
{
    using System;
    using System.Collections.Generic;

    public partial class Services
    {
        public short ServiceID { get; set; }
        public string ServiceName { get; set; }
        public Nullable<decimal> ServicePrice { get; set; }
        public Nullable<System.DateTime> EntryDateTime { get; set; }
        public Nullable<bool> IsOwner { get; set; }
        public Nullable<decimal> Commission { get; set; }
    }
}

View Model

namespace ZahidCarWash.Models
{
    using System;
    using System.Collections.Generic;

    public class ServiceViewModel
    {
        public short ServiceID { get; set; }
        public string ServiceName { get; set; }
        public decimal ServicePrice { get; set; }
        public System.DateTime EntryDateTime { get; set; }
        public bool IsOwner { get; set; }
        public decimal Commission { get; set; }
    }
}

Controller

[HttpPost]
public JsonResult AddServices(ServiceViewModel model)
{
    if(model == null)
       return null;

    var addService = new Services(); 
    //Use Automapper for mapping view models to data entities
    addService.ServiceID = model.ServiceID ;  //Service Id should be auto incremented from database
    addService.ServiceName = model.ServiceName ;
    addService.ServicePrice = model.ServicePrice ;
    addService.EntryDateTime = model.EntryDateTime ;
    addService.IsOwner = model.IsOwner ;
    addService.Commission = model.Commission ;


    ServicesRepository servicesRep = new ServicesRepository();
    int i = 0;
    //i = ServicesRep.UpdateServices(UpdateServicesVM, out ReturnStatus, out ReturnMessage);

    //Don't write the data specific logic in controllers. Use Repository Pattern.
    ZahidCarWashDBEntities context = new ZahidCarWashDBEntities();
    context.Services.Add(addService);
    context.SaveChanges();
    return Json(new { ReturnMessageJSON = ReturnMessage, ReturnStatusJSON = ReturnStatus });  

Note: In the code above, I have described the simple flow to work with View Models and Data Entities in an MVC application. In real world projects, people consider lot more things like Repository Pattern to perform CRUD operation, Separation of Concerns principle (it is not advisable to perform database operations in action methods of a controller). Also to map different entities, we can use Automapper. There are lot of other factors to be checked but you can get an idea about your doubt.

Sahil Sharma
  • 1,813
  • 1
  • 16
  • 37