henkmollema / Dapper-FluentMap

Provides a simple API to fluently map POCO properties to database columns when using Dapper.
MIT License
427 stars 86 forks source link

Invalid column name when executing a command (insert or update) a second time in another entity #102

Closed patricksegantine closed 1 year ago

patricksegantine commented 5 years ago

The exception occurs in the following cases: First: I execute one of the Add or Update commands by passing an entity, for example Customers. and then execute any of the commands on another entity, such as Orders.

No matter the order of execution, the message that appears is invalid column on the second execution.

It seems that the problem is in mapping the base class (Multi Mapping Id) that is in memory generating the exception:

Map (p => p.Id) .IsKey (). ToColumn ("IdActType");

I solved the problem by creating the property in the class and ignoring the base class Id:

public class ActTypeMap: DommelEntityMap      {          public ActTypeMap ()          {              ToTable ("ActType");              Map (p => p.Id) .Ignore();              Map (p => p.IdTypeAto) .IsKey ();          }      }

public abstract class Entity : IEquatable { public Entity() { Id = Guid.NewGuid(); Timestamp = DateTime.Now; }

    public Guid Id { get; set; }
    public Guid IdUser { get; set; }
    public DateTime Timestamp { get; set; }
    public bool Equals(Entity other) => Id == other.Id;
}

public abstract class DapperGenericRepository : IRepository where TEntity : Entity { protected readonly string ConnectionString;

    public DapperGenericRepository()
    {
        if (FluentMapper.EntityMaps.IsEmpty)
        {
            RegisterMappings.Register();
        }

        var config = new ConfigurationBuilder()
            .AddJsonFile("appSettings.json")
            .Build();

        ConnectionString = config.GetConnectionString("DefaultConnection");
    }

    public virtual void Add(TEntity entity)
    {
        entity.Timestamp = DateTime.Now;
        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {
            conn.Open();
            conn.Insert(entity);
        }
    }

    public virtual void Update(TEntity entity)
    {
        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {
            conn.Open();
            conn.Update(entity);
        }
    }

}

public static class RegisterMappings { public static void Register() { FluentMapper.Initialize(c => { c.AddMap(new CustomerMap()); c.AddMap(new ActTypeMap());

            c.ForDommel();
        });
    }
}
snios commented 1 year ago

@henkmollema I got the same issue but cant do the same workaround as you did. Anyone got any input on this?

snios commented 1 year ago

I think this is not an issue in this package. At least for me updating Dapper and Dommel in our project made the issue go away.