0

I'm seeking advice on how best to map models to my view in C#.

The database designer opted for a SQL naming convention using snake case.

Thus, an table might look like:

Client
---------
Id
Client_Name
Client_Number
Is_Active

From what I understand, it's not best standard to use underscores in models/properties, so my models look like:

public class Client
{
    public int Id { get; set; }
    public int ClientNumber { get; set; }
    public int ClientName { get; set; }
    public boolean IsActive{ get; set; }
}

I'm using dapper so usually I just alias the columns like so:

SELECT 
    Id As Id,
    Client_Name AS ClientName,
    Client_Number AS ClientNumber,
    Is_Active AS IsActive
FROM Client

I don't know if this is the best way, but it works for now. Currently, I've translated once.

Now I move to the view. It's an api so usually it is JSON, which uses camelCase.

public JsonResult GetAll()
{
    var clients = clients.GetAll();
    JSON(client);
}

Which sends

{
    id: '0',
    clientName: 'Client1',
    clientNumber: '5555-55555'
    isActive: true
}

So, the format has gotten translated again.

Now I need post to the application.

public JsonResult Add(AddClientViewModel addClientVM)
{

    var client = new Client({
        client.ClientName = addClientVM.clientName;
        client.ClientNumber = addClientVM.clientNumber;
        client.IsActive = addClientVM.isActive;
    })
    // Add client etc...
}

I've basically hit every case there is and just transformed my objects over and over again. Seems very tedious. What's a best practice to minimize the translation and mapping.

Thanks.

user1093111
  • 1,091
  • 5
  • 21
  • 47
  • In your `public JsonResult Add(Client addClientVM)` example, why copy `addClientVM` to `client` when they are the same type? – mjwills Nov 07 '18 at 21:13
  • Does https://stackoverflow.com/questions/28767660/avoiding-camelcasepropertynamescontractresolver-for-a-specific-method help? – mjwills Nov 07 '18 at 21:15
  • Sorry that was supposed to be an AddClientViewModel type. A lot of the time the controller just has args and not necessarily a model, as well. – user1093111 Nov 07 '18 at 21:23
  • And I do use the JSON() method. It makes it lowercase as desired. I guess the place I most want to improve is going from `snake_case` to `PascalCase`. Gotta be a better way – user1093111 Nov 07 '18 at 21:29

0 Answers0