jason.kaisersmith
jason.kaisersmith

Reputation: 9650

Dapper insert: flatten class for insert

I have a class with an embedded subclass such as this

    public class Parent
    {
        public int Id { get; set; }
        public string Name { get;set;}
        public ValidFor ValidFor { get; set; }
    }

    public class ValidFor 
    {
        public DateTime? StartDateTime { get;set;}
        public DateTime? EndDateTime { get; set; }
    }

But upon Insert with Dapper I want to flatten out the ValidFor so that I just insert into a single "Parent" table. My insert code and SQL is below

  public async Task<Category> Create(Category entity)
  {            
      string sql = "Insert into Parent (Id, Name, StartDateTime, EndDateTime) values (@Id, @Name, @StartDateTime, @EndDateTime)";

      using (var connection = GetConnection)
      {
          await connection.ExecuteAsync(sql, entity);
          return entity;
      }
   }

But I am getting the error

"StartDateTime" does not exist

I understand why, but how can I Map my Object to my table? The examples I can find online about Multi-Mapping all focus on multiple tables.

I could of course create a different class which is flat and matches my table structure and then Map between them (using Mapster/Automapper etc.), but as I have 10s of classes with this issue then that is not really practical.

Upvotes: 0

Views: 421

Answers (1)

JHBonarius
JHBonarius

Reputation: 11281

I think something is seriously wrong with your architecture, but anyhow:

The simplest fix is just do specify the parameters manually in an anonymous object.

public async Task<Category> Create(Category entity)
{            
    string sql = "Insert into Parent (Id, Name, StartDateTime, EndDateTime) values (@Id, @Name, @StartDateTime, @EndDateTime)";

    using (var connection = GetConnection)
    {
        await connection.ExecuteAsync(sql, new
        {
            entity.Id,
            entity.Name,
            entity.ValidFor.StartDateTime,
            entity.ValidFor.EndDateTime,
        });
        return entity;
    }
}

Upvotes: 1

Related Questions