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.
Just add the [Computed]
attribute to the properties in question.
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]
.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With