I am trying to create a create method which will insert rows into my database.
This is my database table. As you can see it has an accountId column
CREATE TABLE [dbo].[Transactions](
[Id] [int] NOT NULL,
[AccountId] [int] NULL,
PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
This is my transactions class as you can see the class name is transactions the same as the table and there is an account id column.
public class Transactions
{
public int Id { get; set; }
public int AccountId { get; set; }
}
Here is my create method which should insert a row into the database.
public async Task<int> CreateAsync(Transactions transactions)
{
using var dbConnection = await _connectionFactory.CreateConnectionAsync();
return await dbConnection.ExecuteAsync("""
insert into Transactions (AccountId)
VALUES (@AccountId)
""", new { AccountId = transactions.AccountId});
}
I have also tried to just pass transactions but it didn't work either so I tried. new { AccountId = transactions.AccountId}
As you can see from this image no matter what I do it won't detect the columns.
I have chosen the correct schema, I have also tried to disconnect the database and reconnect again.
I am at a loss as to why this doesn't work. I have another method which is get and passes and Id that works, I also have another service which connects to another table and I can create an insert statement for that table.
This is a known unresolved Rider bug - Rider doesn't understand how Dapper maps properties to query parameters and assumes @AccountId
is a variable. As a comment under the bug shows, this happens with F# and raw ADO.NET as well.
The code itself should run fine. As long as the names of the anonymous type properties match the parameters, the query will work. This code is no different than the code in Dapper's landing page eg:
var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });
or
var count = connection.Execute(@"insert MyTable(colA, colB) values (@a, @b)",
new[] {
new { a=1, b=1 },
new { a=2, b=2 },
new { a=3, b=3 }
}
);
You can use :
new { AccountId = transactions.AccountId}
or
new { transactions.AccountId}