Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring properties in Dapper

Tags:

dapper

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.

like image 865
Pedro Felix Avatar asked Jun 08 '12 10:06

Pedro Felix


4 Answers

Just add the [Computed] attribute to the properties in question.

like image 92
Caltor Avatar answered Oct 08 '22 07:10

Caltor


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].

like image 20
Forest Johnson Avatar answered Oct 08 '22 06:10

Forest Johnson


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.

like image 35
Sam Saffron Avatar answered Oct 08 '22 06:10

Sam Saffron


If you just want to "hide" a property from your Insert/Update statements then there is one official way to do this in dapper extensions:

using DapperExtensions.Mapper;

    public class UserMapper : ClassMapper<User>
        {
            public UserMapper()
            {
                base.Map(m => m.IsTrialUser).Ignore();
                base.AutoMap();
            }
        }
like image 35
Elisabeth Avatar answered Oct 08 '22 08:10

Elisabeth