Search code examples
c#asp.netdapper

Mapping with Dapper


I am doing a one month job in my summer-holidays and I have to use dapper to map a model. I've watched several videos and I really don´t understand how it works. I just want to simply map the whole Model with an asp.net web api.

My two models are down below and I have already installed Dapper.

I tried to watch some videos and google my problem, but none of them explains it in the way I would understand it.

Facility class :

namespace DataImportWebService.Models
{
    public class Facility
    {
        public string Name { get; set; }

        public string Date { get; set; }

        public string FeedbackType { get; set; }

        public int Count { get; set; }
    }
}

Measurement class:

namespace DataImportWebService.Models
{
    public class Measurement
    {
        public string MeasurementDate { get; set; }

        public string Name { get; set; }

        public string MeasurementName { get; set; }

        public decimal MeasuerementValue { get; set; }
    }
}

I hope to get an explanation or some code. Thank you!


Solution

  • It sounds like you're simply trying to figure out how to use dapper. There's lots of documentation out there https://dapper-tutorial.net/dapper. For your 2 objects if you're simply trying to map data from a database into those objects then it's fairly simple.

    I often create a base repository class that contains all the different versions I might want to run. The most basic would probably be:

    protected IEnumerable<T> ExecuteQuery<T>(string query, object parameters = null, CommandType? commandType = null)
    {
        using (var conn = Connection)
        {
            return conn.Query<T>(query, parameters, commandType: commandType, commandTimeout: 0);
        }
    }
    

    This can then be used in other repositories and used like this:

    ExecuteQuery<YourObjectToMapTo>(YourSQLQuery, YourParameters);
    

    This will return an IEnumerable of your object, even if it only gets 1. To only return 1 just stick First() or FirstOrDefault() on the end.