Inserting an IEnumerable collection with Dapper errors out with “class is not supported by Dapper.”

后端 未结 1 1094
执笔经年
执笔经年 2020-12-13 02:41

Yep, there are questions here and here about how to insert records with dapper-dot-net. However, the answers, while informative, didn\'t seem to point me in the right direct

1条回答
  •  天涯浪人
    2020-12-13 03:19

    I just added a test for this:

    class Student
    {
        public string Name {get; set;}
        public int Age { get; set; }
    }
    
    public void TestExecuteMultipleCommandStrongType()
    {
        connection.Execute("create table #t(Name nvarchar(max), Age int)");
        int tally = connection.Execute(@"insert #t (Name,Age) values(@Name, @Age)", new List 
        {
            new Student{Age = 1, Name = "sam"},
            new Student{Age = 2, Name = "bob"}
        });
        int sum = connection.Query("select sum(Age) from #t drop table #t").First();
        tally.IsEqualTo(2);
        sum.IsEqualTo(3);
    }
    

    It works as advertised. I made a few amendments to the way multi-exec works (so its a tad faster and supports object[]).

    My guess is you were having issues cause you were missing a getter property on all you fields on WTUser. All params must have reader properties, we do not support pulling this from fields, it would require a complex parsing step to stay efficient.


    An additional point that caused an issue is passing dapper a param with unsupported mapping.

    For example, the following class is not supported as a param:

    class Test
    {
       public int Id { get; set; }
       public User User {get; set;}
    }
    
    cnn.Query("select * from Tests where Id = @Id", new Test{Id = 1}); // used to go boom 
    

    The issue is that dapper did not parse the SQL, it assumed all the props are settable as params but was unable to resolve the SQL type for User.

    Latest rev resolves this

    0 讨论(0)
提交回复
热议问题