dapperdapper-fastcrud

Dapper FastCRUD with object inheritance


I am using Dapper FastCRUD for insert/update for my project. I have a entity which inherits from another entity. Both of them have separate destination tables, annotated with TableAttribute. Is there a way to save data to both the tables using Fast CRUD, if I have an object of type, which is the inherited class?


Solution

  • unfortunately I don't think we can expect Dapper FastCRUD or any of the common dapper extensions to handle object inheritance in that way - I've played with a few and no luck.

    Best I could come up with was to call Convert.ChangeType before I handover to Dapper to perform the requested operation.

    For example, I like to keep my database interactions separate from my business logic. The idea being that I can easily swap out the ORM for another one without going anywhere near my business logic.

    public void Create<T>(T bo) where T : BusinessObject
    {
        var castedBo = (T)Convert.ChangeType(bo, typeof(T));
        Connection.Insert(castedBo);
    }
    

    My Object I'm trying to persist extends BusinessObject

    Table("Blog")]
    public class Blog : BusinessObject {
     ...
    }
    

    and I can then persist my object like so

    Blog blog = new Blog();
    dataMapper.Create(Blog)
    

    Hope this helps!