How to protect yourself from accidental typos when defining entity classes for Dapper?

59 views Asked by At

In the code below, I've purposely made a spelling error for ProductID (xxxxSpelledWrong) and of course Dapper will happily load what it can from the database into the class based on matching column to property names, so now I'm a bit worried.

Other than brute force approach of writing tests to check every single column / property pair for every entity I'm dealing with, is there some more clever way to get a reasonable level of certainty that you haven't made any spelling mistakes in your entities (or column names have changed in the underlying database?

var products = conn.Query<Product>(@"select top 100 * from Production.Product");

        public partial class Product
        {
            public int ProductID_xxxxSpelledWrong { get; set; }
            public string Name { get; set; }
            public string ProductNumber { get; set; }
            public bool MakeFlag { get; set; }
            public bool FinishedGoodsFlag { get; set; }
            public string Color { get; set; }
            public int SafetyStockLevel { get; set; }
            public int ReorderPoint { get; set; }
            public decimal StandardCost { get; set; }
            public decimal ListPrice { get; set; }
            public string Size { get; set; }
            public string SizeUnitMeasureCode { get; set; }
            public string WeightUnitMeasureCode { get; set; }
            public decimal? Weight { get; set; }
            public int DaysToManufacture { get; set; }
            public string ProductLine { get; set; }
            public string Class { get; set; }
            public string Style { get; set; }
            public int? ProductSubcategoryID { get; set; }
            public int? ProductModelID { get; set; }
            public DateTime SellStartDate { get; set; }
            public DateTime? SellEndDate { get; set; }
            public DateTime? DiscontinuedDate { get; set; }
            public DateTime ModifiedDate { get; set; }    
        }
1

There are 1 answers

2
CaffGeek On

If your class matches your table, why write it? Use a t4 template to generate it.

Something like this should work: https://www.nuget.org/packages/Dapper.SimpleCRUD.ModelGenerator/

Documentation at: https://github.com/ericdc1/Dapper.SimpleCRUD/wiki/T4-Template