C#C
C#3y ago
BekirK

✅ Dapper Generic Repository Error in Insert Method (SOLVED)

public void Insert(Entity entity)
    {
        using (var connection = dbContext.CreateConnection())
        {
            string tableName = typeof(Entity).Name;
            PropertyInfo[] properties = typeof(Entity).GetProperties();

            string columns = string.Join(", ", properties.Select(p => p.Name));
            string parameters = string.Join(", ", properties.Select(p => "@" + p.Name));
            string query = $"INSERT INTO {tableName} ({columns}) VALUES ({parameters})";
            // Query result: INSERT INTO Category (Name, [Order], Id, CreatedAt, CreatedBy, UpdatedAt, UpdatedBy) 
VALUES (@Name, @[Order], @Id, @CreatedAt, @CreatedBy, @UpdatedAt, @UpdatedBy)

            query = query.Replace("Order", "[Order]");  // I added a replace restriction because it is a special name in Order SQL.

            connection.Execute(query, entity);
        }
    }


ERROR: Microsoft.Data.SqlClient.SqlException: 'Must declare the scalar variable "@".'

Hello everyone, I'm coding a Generic Repository with Dapper (database: MSSQL). I coded the Get and Delete operations, but I am getting the above error in the Insert operation. How do I solve this error?
error.png
Was this page helpful?