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

后端 未结 8 899
忘掉有多难
忘掉有多难 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(object param)
        {
            using (SqlConnection conn = new SqlConnection(GetConnectionString()))
            {
                conn.Open();
                conn.Create((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));
            }
        }
    

提交回复
热议问题