Ignoring properties in Dapper

dapper

Question

In Dapper (http://code.google.com/p/dapper-dot-net/), is there a way to ignore properties in the model class, namely when using the Insert extension method? My model class has a set of computed properties which are not persisted in the associated table.

Thanks. Pedro

Accepted Answer

Well, Dapper has no Insert extension method, that is in dapper.contrib, dapper extensions or dapper rainbow.

Dapper itself allows you to do:

Animal a = new Animal {Age = 10, Family = "Canine"}
// only insert Age
cnn.Execute("insert Animal(Age) values (@Age)", a); 

To work around for some of the extension classes you can sometimes do:

cnn.InsertExtension("Animal", new{a.Age});

Regardless, you can always fall back to raw Dapper for your complex filtered inserts.


Popular Answer

If you are using Dapper.Contrib, check out this code in SqlMapperExtensions:

https://github.com/StackExchange/dapper-dot-net/blob/master/Dapper.Contrib/SqlMapperExtensions.cs#L54-L66

        private static List<PropertyInfo> ComputedPropertiesCache(Type type)
        {
            //...
            var computedProperties = TypePropertiesCache(type).Where(p => p.GetCustomAttributes(true).Any(a => a is ComputedAttribute)).ToList();

and https://github.com/StackExchange/dapper-dot-net/blob/master/Dapper.Contrib/SqlMapperExtensions.Async.cs#L147-L165

        var computedProperties = ComputedPropertiesCache(type);
        var allPropertiesExceptKeyAndComputed = allProperties.Except(keyProperties.Union(computedProperties)).ToList();
        //...
        for (var i = 0; i < allPropertiesExceptKeyAndComputed.Count; i++)
        {
            //...

So if you add a ComputedAttribute to your properties on your class, Dapper.Contrib won't try to insert them in to the database! You shouldn't have to worry about getting Dapper to ignore those properties, only Dapper.Contrib. Because if you use select * from tablename in your dapper queries,it will only try to map columns that exist. So you just don't create columns for the properties which you marked as [Computed].




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why