Reputation: 33
I am currently trying to setup work with MySQL db via dapper.
I have declared POCO for dapper:
public class DevicesOnTesterDbTable
{
public string UUID { get; set; }
public string DeviceType { get; set; }
public string DeviceAddedAt { get; set; }
public uint Address { get; set; }
}
I also have Dapper.Fluent EntityMap for that table:
public class DevicesOnTesterDbTableMap : EntityMap<DevicesOnTesterDbTable>
{
public DevicesOnTesterDbTableMap()
{
Map(p => p.UUID).ToColumn("devices_on_tester_uuid");
Map(p => p.DeviceType).ToColumn("devices_on_tester_type");
Map(p => p.DeviceAddedAt).ToColumn("devices_on_tester_add_at");
Map(p => p.Address).ToColumn("devices_on_tester_address");
}
}
My database have about ten tables so i have ten pairs of POCO and EntityMap classes for them. So in case of reading i have to perform something like this for each table:
public static List<DevicesOnTesterDbTable> ReadDevices(string server)
{
FluentMapper.Initialize(config =>
{
config.AddMap(new DevicesOnTesterDbTableMap());
});
try
{
using (var mySqlConnection = OpenConnection(server))
{
mySqlConnection.Open();
return mySqlConnection.Query<DevicesOnTesterDbTable>("Select * from power_source_calibration").ToList();
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
Now is there a way to pass this pairs into some other method that will perform common operations such as read\write\update etc? Or maybe there is some better way around?
Upvotes: 3
Views: 2498
Reputation: 16408
There is a better way around; actually you are doing it wrong.
You do not need to call FluentMapper.Initialize
in each of your method like ReadDevices
. Ideally, all your mappings (for all entities) should happen only once at the startup of your application.
Following is from here:
Initialize your mapping at the start of your application.
FluentMapper.Initialize(config => { config.AddMap(new InvoiceMap()); });
Also, refer this question which shows how to do it at application startup. Refer Register()
method which is static
and caller call it once at application startup somewhere.
Upvotes: 4