© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
9 replies
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);
        }
    }
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
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

EF Core - Generic repository update method
C#CC# / help
4y ago
❔ generic class in generic method
C#CC# / help
3y ago
❔ is Generic Repository a bad implementation of Repository Pattern?
C#CC# / help
4y ago
✅ Specialising a generic method
C#CC# / help
4y ago