How do I perform an insert and return inserted identity with Dapper?

后端 未结 8 831
忘掉有多难
忘掉有多难 2020-11-28 01:45

How do I perform an insert to database and return inserted identity with Dapper?

I\'ve tried something like this:

string sql = \"DECLARE @ID int; \"          


        
相关标签:
8条回答
  • 2020-11-28 02:12

    If you're using Dapper.SimpleSave:

     //no safety checks
     public static int Create<T>(object param)
        {
            using (SqlConnection conn = new SqlConnection(GetConnectionString()))
            {
                conn.Open();
                conn.Create<T>((T)param);
                return (int) (((T)param).GetType().GetProperties().Where(
                        x => x.CustomAttributes.Where(
                            y=>y.AttributeType.GetType() == typeof(Dapper.SimpleSave.PrimaryKeyAttribute).GetType()).Count()==1).First().GetValue(param));
            }
        }
    
    0 讨论(0)
  • 2020-11-28 02:15

    A late answer, but here is an alternative to the SCOPE_IDENTITY() answers that we ended up using: OUTPUT INSERTED

    Return only ID of inserted object:

    It allows you to get all or some attributes of the inserted row:

    string insertUserSql = @"INSERT INTO dbo.[User](Username, Phone, Email)
                            OUTPUT INSERTED.[Id]
                            VALUES(@Username, @Phone, @Email);";
    
    int newUserId = conn.QuerySingle<int>(
                                    insertUserSql,
                                    new
                                    {
                                        Username = "lorem ipsum",
                                        Phone = "555-123",
                                        Email = "lorem ipsum"
                                    },
                                    tran);
    

    Return inserted object with ID:

    If you wanted you could get Phone and Email or even the whole inserted row:

    string insertUserSql = @"INSERT INTO dbo.[User](Username, Phone, Email)
                            OUTPUT INSERTED.*
                            VALUES(@Username, @Phone, @Email);";
    
    User newUser = conn.QuerySingle<User>(
                                    insertUserSql,
                                    new
                                    {
                                        Username = "lorem ipsum",
                                        Phone = "555-123",
                                        Email = "lorem ipsum"
                                    },
                                    tran);
    

    Also, with this you can return data of deleted or updated rows. Just be careful if you are using triggers because (from link mentioned before):

    Columns returned from OUTPUT reflect the data as it is after the INSERT, UPDATE, or DELETE statement has completed but before triggers are executed.

    For INSTEAD OF triggers, the returned results are generated as if the INSERT, UPDATE, or DELETE had actually occurred, even if no modifications take place as the result of the trigger operation. If a statement that includes an OUTPUT clause is used inside the body of a trigger, table aliases must be used to reference the trigger inserted and deleted tables to avoid duplicating column references with the INSERTED and DELETED tables associated with OUTPUT.

    More on it in the docs: link

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