Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not update a certain property on Update method with dapper extensions

I know I can use the pure dapper to build my update string with only the properties I want to update (whitelist).

What I want is to keep the ORM style of dapper extensions:

con.Update<Person>(person);

I want that some properties of person are not updated (blacklist)

How can I exlude properties from being updated running the .Update extension method?

Do you maybe know of a better .Update extension in the dapper style? (Then I dont have to

write it ;-)

like image 695
Elisabeth Avatar asked Oct 21 '22 21:10

Elisabeth


2 Answers

Just define a PersonMapper that inherits from ClassMapper<Person> and use Ignore() to Map the columns you want to exclude.

See example below (source: github tests for Dapper Extensions ) where the Phones property ( IEnumerable<Phone> Phones ) is excluded.

using System;
using System.Collections.Generic;
using DapperExtensions.Mapper;

namespace DapperExtensions.Test.Data
{
    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DateCreated { get; set; }
        public bool Active { get; set; }
        public IEnumerable<Phone> Phones { get; private set; }
    }

    public class Phone
    {
        public int Id { get; set; }
        public string Value { get; set; }
    }

    public class PersonMapper : ClassMapper<Person>
    {
        public PersonMapper()
        {
            Table("Person");
            Map(m => m.Phones).Ignore();
            AutoMap();
        }
    }
}
like image 75
Shiva Avatar answered Oct 23 '22 23:10

Shiva


In the ClassMapper for the relevant type, do this:

public MyTableMapper()
{
    Table("MyTable");
    Map(f => f.MyCalculatedField).ReadOnly();
}
like image 20
tomfanning Avatar answered Oct 23 '22 23:10

tomfanning