3

I have table User

CREATE TABLE [User](
    [Id] [int] primary key NOT NULL,
    [Username] [nvarchar](50) NULL,
    [EmailID] [nvarchar](50) NULL)

User class

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public string EmailID { get; set; }
}

code

var usr=new User();
usr.Id=1;
usr.Username="jhon";
usr.EmailID="j@gmail.com";
_dbConnection.Insert<User>(usr);

The above code throwing null exception.Table with identity working fine.

Stack Trace:

at Dapper.SimpleCRUD.Insert[TKey](IDbConnection connection, Object entityToInsert, IDbTransaction transaction, Nullable`1 commandTimeout)

Error Message:

An exception of type 'System.Exception' occurred in Dapper.SimpleCRUD.dll but was not handled in user code Additional information: Invalid return type

Void Ray
  • 9,849
  • 4
  • 33
  • 53
Deepak Saralaya
  • 457
  • 4
  • 12

2 Answers2

7

I ran into the same issue today. It's because you're specifying the type to be inserted instead of specifying the return type which would be int. With that said however you don't even need to specify the type.

Your code can be simplified to:

var usr=new User();
usr.Id=1;
usr.Username="jhon";
usr.EmailID="j@gmail.com";
_dbConnection.Insert(usr);
Scott Thornton
  • 136
  • 1
  • 7
4

Here's the correct answer from https://github.com/ericdc1/Dapper.SimpleCRUD

[Required] - By default the [Key] property is not inserted as it is expected to be an autoincremented by the database. You can mark a property as a [Key] and [Required] if you want to specify the value yourself during the insert.

In my case, my primary key is a long / bigint:

    [Key]
    [Required]
    public long MyPrimaryKey { get; set; }

And T in Insert<T> needs to match the return type (long):

connection.Insert<long>(model);
Chris Klepeis
  • 9,783
  • 16
  • 83
  • 149