简体   繁体   中英

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!

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.

What you need understand is that Dapper is only a thin wrapper on top of ADODB.NET . It's nothing like Entity Framework. Dapper doesn't now your database structure, it doesn't do SQL for you. You create the database and write all the SQL. Dapper helps your by adding a lot of extension methods to your connection. The extension methods take all the tedious DataReader stuff from ADODB.NET and hide it away, making it possible for you to just fire a select to the database and have a nice list returned where database columns have been mapped to your entity. If your entity properties and database columns are named the same, there is actually very little to it. I urge you to go through the tutorial in @sr28's answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM