Dapper Extension Get & Update returns errors

dapper dapper-extensions

Question

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

Popular Answer

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 })


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow