2

I tried to play with Dapper Extension & MS Access and succeeded up to certain extent. My code is listed below. All the functions works properly (Insert/Count/GetList/Delete) except Get & Update. I have summarised the code below. If anybody wants I can paste all the code here

My Product class

public class Products
{
    public string ProductNumber { get; set; }
    public string Description { get; set; }
}

And in my main class. I tried to get the product and update it as below. con.Get<Products> function returns an exception with "Sequence contains more than one element" message and con.Update<Products> returns an exception with "At least one Key column must be defined".

        using (var con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb"))
        {

            string ProductNumber = "12";
            var product4 = con.Get<Products>(ProductNumber);
            product4.ProductNumber = "Baz";
            con.Update<Products>(product4);   

            Console.ReadLine();
        }

Even though con.Get<Products> fails con.GetList<Products>(predicate) works perfectly. I did follow this link for setup

RobinAtTech
  • 1,299
  • 3
  • 22
  • 48
  • Can you show the code for `con.Get` and `con.Update`? – stefankmitph Sep 05 '16 at 15:09
  • 2
    The .Get and .Update methods are extension methods from DapperExtensions. For an update, DapperExtensions needs to know what the key property is for the class. It would normally infer it from a property called ID or if you had a custom [mapper](https://github.com/tmsmith/Dapper-Extensions/wiki/Customized-mapping-for-a-class) – G Davison Sep 05 '16 at 16:31
  • @GDavison Any sample code for it? – RobinAtTech Sep 05 '16 at 22:51

1 Answers1

4

If DapperExtensions can't infer a key property called ID from your class, you'll need to explicitly specify one via a class mapper. Assuming the ProductNumber is the primary key in the database, the following example class mapper should set the ProductNumber to be the primary key for DapperExtensions.

using Dapper;   
using DapperExtensions;
using DapperExtensions.Mapper;
public class ProductsMapper : ClassMapper<Products>
{
    public ProductsMapper()
    {
        Map(x => x.ProductNumber).Key(KeyType.Assigned);
        AutoMap();
    }
}

This class can sit somewhere within the same assembly as the rest of your code. Dapper Extensions will automatically pick it up. If you have your classes and Dapper code in separate assemblies, you can point it to your mapper with the following line:

DapperExtensions.DapperExtensions.SetMappingAssemblies({ typeof(ProductsMapper).Assembly })
G Davison
  • 1,079
  • 1
  • 14
  • 21