• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Dapper.DynamicParameters类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Dapper.DynamicParameters的典型用法代码示例。如果您正苦于以下问题:C# DynamicParameters类的具体用法?C# DynamicParameters怎么用?C# DynamicParameters使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



DynamicParameters类属于Dapper命名空间,在下文中一共展示了DynamicParameters类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: CustomerInsert

        /// <summary>
        /// 添加 Customer
        /// </summary>
        public bool CustomerInsert(Customer model)
        {
            string sql = @"
                            INSERT INTO Customer
                            (
	                            Id,CustomerName,AddTime,IsDelete,CustomerLevel,
	                            PhoneNo,Token,VipPrice,Remark
                            )
                            VALUES
                            (
	                            @Id,@CustomerName,@AddTime,@IsDelete,@CustomerLevel,
	                            @PhoneNo,@Token,@VipPrice,@Remark
                            )
                            ";

            DynamicParameters param = new DynamicParameters();
            param.Add("@Id", model.Id, DbType.Guid);
            param.Add("@CustomerName", model.CustomerName, DbType.String);
            param.Add("@AddTime", model.AddTime, DbType.DateTime);
            param.Add("@IsDelete", model.IsDelete, DbType.Boolean);
            param.Add("@CustomerLevel", model.CustomerLevel, DbType.Byte);
            param.Add("@PhoneNo", model.PhoneNo, DbType.String);
            param.Add("@Token", model.Token, DbType.String);
            param.Add("@VipPrice", model.VipPrice, DbType.Double);
            param.Add("@Remark", model.Remark, DbType.String);


            var result = DataBaseAccessCommand.ExecuteCommand(sql, param);

            return result < 0 ? false : true;
        }
开发者ID:RoseLiu,项目名称:OnePiece.DataAccess,代码行数:34,代码来源:CustomerDAL.cs


示例2: TestSave

        public void TestSave()
        {
            var cedarContext = Cedar.CedarAppStore.Instance.GetContextOf("IGD");
            long uid = 0;

            if (cedarContext.IsSetupSchemaRequired)
            {
                cedarContext.SetupSchema(new ShardStartegyData() { StrategyType = Strategy.Sequential });

            }
            uid = cedarContext.CurrentShard;

            long? uId = 0;

            var worker = new Cedar.IdWorker(uid);
            uId = worker.GetUniqueId();

            using (ICedarSession cedarSession = new Cedar.AppContext("IGD").GetSession(uId.Value))
            {
                var parameters = new DynamicParameters();
                parameters.Add("firstName", "TArun");
                parameters.Add("lastName", "Kumar");
                cedarSession.Insert("usp_addemployee", parameters, commandType: Cedar.CommandType.StoredProcedure);
            }
        }
开发者ID:Vadi,项目名称:Cedar,代码行数:25,代码来源:CedarSessionTest.cs


示例3: Insert

        public static async Task<long> Insert(Device device)
        {
            const string commandText = @" Insert into Devices (Id, ClientId, RequestDeviceId, IsActived, DeviceKey, DeviceSecret, SerialNumber, IMEI, Manufacturer, Model, Platform, PlatformVersion, DeviceName, DeviceDescription) 
                                         values (@id, @clientId, @requestDeviceId, @isActived, @deviceKey, @deviceSecret, @serialNumber, @iMEI, @manufacturer, @model, @platform, @platformVersion, @deviceName, @deviceDescription)";
            var parameters = new DynamicParameters();
            if (device.Id > 0)
                parameters.Add("id", device.Id);
            else
                parameters.Add("id",0);
            parameters.Add("clientId", device.ClientId);
            parameters.Add("requestDeviceId", device.RequestDeviceId);
            parameters.Add("isActived", device.IsActived ? 1 : 0);
            parameters.Add("deviceKey", device.DeviceKey);
            parameters.Add("deviceSecret", device.DeviceSecret);
            parameters.Add("serialNumber", device.SerialNumber);
            parameters.Add("iMEI", device.IMEI);
            parameters.Add("manufacturer", device.Manufacturer);
            parameters.Add("model", device.Model);
            parameters.Add("platform", device.Platform);
            parameters.Add("platformVersion", device.PlatformVersion);
            parameters.Add("deviceName", device.DeviceName);
            parameters.Add("deviceDescription", device.DeviceDescription);
            long results;
            using (var conn = await DataAccessBase.GetOpenAsync(DataAccessBase.QuangAuthConn))
            {

                var data = await conn.QueryAsync<long>(commandText, parameters);
                results = data.FirstOrDefault();
            }
            return results;
        }
开发者ID:quangnc0503h,项目名称:ecommerce,代码行数:31,代码来源:DeviceDal.cs


示例4: QuerySql

        public IEnumerable<dynamic> QuerySql(string sql, object p1, Dictionary<string, string> d)
        {
            var cn = GetReadonlyConnection();
            var parameters = new DynamicParameters();
            parameters.Add("@p1", p1 ?? "");
            if (d != null)
                foreach (var kv in d)
                    parameters.Add("@" + kv.Key, kv.Value);

            if (sql.Contains("@UserPeopleId"))
                parameters.Add("@UserPeopleId", data.PeopleId ?? Util.UserPeopleId);
            if (sql.Contains("@CurrentOrgId"))
                parameters.Add("@CurrentOrgId", data.OrgId ?? db.CurrentOrgId0);

            if (sql.Contains("@BlueToolbarTagId"))
                if (dictionary.ContainsKey("BlueToolbarGuid"))
                {
                    var guid = (dictionary["BlueToolbarGuid"] as string).ToGuid();
                    if (!guid.HasValue)
                        throw new Exception("missing BlueToolbar Information");
                    var j = db.PeopleQuery(guid.Value).Select(vv => vv.PeopleId).Take(1000);
                    var tag = db.PopulateTemporaryTag(j);
                    parameters.Add("@BlueToolbarTagId", tag.Id);
                }

            return cn.Query(sql, parameters, commandTimeout: 300);
        }
开发者ID:bvcms,项目名称:bvcms,代码行数:27,代码来源:Query.cs


示例5: EditUser

        public void EditUser(EditUserRequest editUser)
        {
            using (var cn = new SqlConnection(Settings.GetConnectionString()))
            {
                var p = new DynamicParameters();
                p.Add("@UserId", editUser.LmsUser.UserId);
                p.Add("@IsStudent", editUser.IsStudent ? 1 : 0);
                p.Add("@IsParent", editUser.IsParent ? 1 : 0);
                p.Add("@IsTeacher", editUser.IsTeacher ? 1 : 0);
                p.Add("@IsAdmin", editUser.IsAdmin ? 1 : 0);

                cn.Execute("spUpdateUserRoles", p, commandType: CommandType.StoredProcedure);

                var p2 = new DynamicParameters();
                p2.Add("@UserId", editUser.LmsUser.UserId);
                p2.Add("@LastName", editUser.LmsUser.LastName);
                p2.Add("@FirstName", editUser.LmsUser.FirstName);
                p2.Add("@Email", editUser.LmsUser.Email);
                p2.Add("@SuggestedRole", editUser.LmsUser.SuggestedRole);
                p2.Add("@GradeLevelId", editUser.LmsUser.GradeLevelId);

                cn.Execute("spUpdateUserDetails", p2, commandType: CommandType.StoredProcedure);

            }
        }
开发者ID:jmullins1992,项目名称:Portfolio,代码行数:25,代码来源:SqlLmsUserRepository.cs


示例6: SqlServerDistributedLock

        public SqlServerDistributedLock(string resource, TimeSpan timeout, IDbConnection connection)
        {
            if (String.IsNullOrEmpty(resource)) throw new ArgumentNullException("resource");
            if (connection == null) throw new ArgumentNullException("connection");

            _resource = resource;
            _connection = connection;

            var parameters = new DynamicParameters();
            parameters.Add("@Resource", _resource);
            parameters.Add("@DbPrincipal", "public");
            parameters.Add("@LockMode", LockMode);
            parameters.Add("@LockOwner", LockOwner);
            parameters.Add("@LockTimeout", timeout.TotalMilliseconds);
            parameters.Add("@Result", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

            connection.Execute(
                @"sp_getapplock", 
                parameters, 
                commandType: CommandType.StoredProcedure);

            var lockResult = parameters.Get<int>("@Result");

            if (lockResult < 0)
            {
                throw new SqlServerDistributedLockException(
                    String.Format(
                    "Could not place a lock on the resource '{0}': {1}.",
                    _resource,
                    LockErrorMessages.ContainsKey(lockResult) 
                        ? LockErrorMessages[lockResult]
                        : String.Format("Server returned the '{0}' error.", lockResult)));
            }
        }
开发者ID:henningst,项目名称:HangFire,代码行数:34,代码来源:SqlServerDistributedLock.cs


示例7: DeletePost

        public void DeletePost(int postID)
        {
            using (SqlConnection cn = new SqlConnection(Settings.ConnectionString))
            {
                var p = new DynamicParameters();

                try
                {
                    p.Add("PostID", postID);

                    cn.Execute("DeletePost", p, commandType: CommandType.StoredProcedure);

                }
                //catch (Exception e)
                //{
                //    // Write failure to database
                //    var ep = new DynamicParameters();

                //    ep.Add("ExceptionType", e.GetType());
                //    ep.Add("ExceptionMessage", e.Message);
                //    cn.Execute("AddError", ep, commandType: CommandType.StoredProcedure);
                //}
                finally
                {
                    cn.Close();
                }
            }
        }
开发者ID:anti0xidant,项目名称:Fitlosophi,代码行数:28,代码来源:Delete.cs


示例8: EditPage

        public void EditPage(StaticPage staticPage)
        {
            using (SqlConnection cn = new SqlConnection(Settings.ConnectionString))
            {
                var p = new DynamicParameters();

                try
                {
                    p.Add("StaticPageID", staticPage.StaticPageID);
                    p.Add("ButtonName", staticPage.ButtonName);
                    p.Add("UserID", staticPage.UserID);
                    p.Add("Body", staticPage.Body);

                    cn.Execute("EditPage", p, commandType: CommandType.StoredProcedure);

                }
                //catch (Exception e)
                //{
                //    // Write failure to database
                //    var ep = new DynamicParameters();

                //    ep.Add("ExceptionType", e.GetType());
                //    ep.Add("ExceptionMessage", e.Message);
                //    cn.Execute("AddError", ep, commandType: CommandType.StoredProcedure);
                //}
                finally
                {
                    cn.Close();
                }
            }
        }
开发者ID:anti0xidant,项目名称:Fitlosophi,代码行数:31,代码来源:Update.cs


示例9: Insert

 public int Insert(GroupSaleVehicle poco, IDbConnection connection)
 {
     var dynamicParams = new DynamicParameters(mapper.Map(poco));
     dynamicParams.Add("@VehicleID", dbType: DbType.Int32, direction: ParameterDirection.Output);
     connection.Execute("InsertSaleVehicle7", dynamicParams ,commandType: CommandType.StoredProcedure);
     return dynamicParams.Get<int>("@VehicleID");
 }
开发者ID:coderasm,项目名称:ABSBuybackMVCWebAPI,代码行数:7,代码来源:GSVRepository.cs


示例10: Find

        public Movie Find(int id)
        {
            var dbArgs = new DynamicParameters();
            dbArgs.Add("id", id);

            return this.db.Query<Movie>("select * from movies where [email protected]", dbArgs).First();
        }
开发者ID:vikshab,项目名称:Visual-Studio,代码行数:7,代码来源:MovieRepository.cs


示例11: SurveyQuestion_Edit

        public static SurveyQuestion SurveyQuestion_Edit(SurveyQuestion model)
        {
            try
            {
                using (var conn = DbHelper.CCService())
                {
                    var p = new DynamicParameters();
                   p.Add("@QuestionID", model.QuestionID);
                    p.Add("@SurveyID", model.SurveyID);
                    p.Add("@Type", model.Type);
                    p.Add("@Conten", model.Conten);
                    p.Add("@IsMust", model.IsMust);
                    p.Add("@IsRandom", model.IsRandom);
                    p.Add("@MinSel", model.MinSel);
                    p.Add("@MaxSel", model.MaxSel);
                    p.Add("@UserID", model.UserID);
                    p.Add("@IsSample", model.IsSample);
                    p.Add("@ChoiceItems", model.ChoiceItems);
                    p.Add("@ChildQuestions", model.ChildQuestions);
                    p.Add("@Orde",model.Orde);
                    conn.Execute("SurveyQuestion_Edit", p, commandType: CommandType.StoredProcedure);
                    //model.QuestionID = p.Get<Int32>("QuestionID");
                    return model;

                }
            }
            catch (Exception e)
            {
                return null;
            }
        }
开发者ID:holdbase,项目名称:IES2,代码行数:31,代码来源:SurveyQuestionDAL.cs


示例12: Get

        public IEnumerable<EventData> Get(Guid aggregateRootId)
        {
            var @params = new DynamicParameters();
            @params.Add("@AggregateRootId", aggregateRootId);

            return _context.Connection.Query<EventData>("[EventStore].[GetEvents]", @params, _databaseTransaction, commandType: CommandType.StoredProcedure);
        }
开发者ID:Lampart071,项目名称:DHub.CQRS,代码行数:7,代码来源:EventStore.cs


示例13: GetReleaseOverviewData

 public OverviewDataModel GetReleaseOverviewData(string includedReleasePathIDs)
 {
     var data = new OverviewDataModel { LastRefresh = DateTime.Now };
     string[] pathIDs = includedReleasePathIDs != null ? includedReleasePathIDs.Split(new[] { ',' }) : null;
     DynamicParameters queryArguments = new DynamicParameters();
     if (pathIDs != null)
     {
         for (int paramNo = 0; paramNo < pathIDs.Length; paramNo++)
         {
             queryArguments.Add(String.Format("p{0}", paramNo), pathIDs[paramNo]);
         }
     }
     using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ReleaseManagement"].ConnectionString))
     {
         var sql = GenerateOverviewSQL(pathIDs != null ? pathIDs.Length : 0);
         using (var multi = connection.QueryMultiple(sql, queryArguments))
         {
             data.ReleasePaths = multi.Read<ReleasePath>().ToList();
             data.Stages = multi.Read<OverviewStage>().ToList();
             data.StageDetails = multi.Read<OverviewStageDetails>().ToList();
             data.ReleaseComponents = multi.Read<Component>().ToList();
         }
     }
     return data;
 }
开发者ID:jvdbovenkamp,项目名称:msrm-dashboard,代码行数:25,代码来源:ReleaseRepository.cs


示例14: UpdateUnitWiseProductAllotment

        public bool UpdateUnitWiseProductAllotment(Hashtable ht)
        {
            int res = 0;
            try
            {
                var sql = "[dbo].[UnitWiseProductAllotmentUpdate]";
                DynamicParameters param = new DynamicParameters();
                param.Add("@userid", ht["userid"]);
                param.Add("@ip", ht["ip"]);
                param.Add("@id", ht["id"]);
                param.Add("@field", ht["field"]);
                param.Add("@value", ht["value"]);

                cn.Open();
                res = cn.Execute(sql, param, commandType: CommandType.StoredProcedure);
                cn.Close();

            }
            catch (Exception ex)
            {

            }
            finally
            {
                cn.Close();
            }
            return Convert.ToBoolean(res);
        }
开发者ID:ganeshsun1991,项目名称:TestProject,代码行数:28,代码来源:CardDatadao.cs


示例15: Retrieve

        public Region Retrieve(int id)
        {
            var p = new DynamicParameters();
            p.Add("RegionID", id);

            return _cn.Query<Region>("SELECT * FROM Region WHERE RegionID = @RegionID", p).SingleOrDefault();
        }
开发者ID:jimxshaw,项目名称:DapperWithNorthwindDB,代码行数:7,代码来源:RegionRepo.cs


示例16: a_menu_is_good

        public void a_menu_is_good()
        {
            //Arrange
            string SqlQuery;
            //IEnumerable<SearchTime> fav;
            SearchTime fav;
            Stopwatch stopwatch = new Stopwatch();

            //act
            stopwatch.Start();
            using (DbConnection sqlConnection = GetOpenConnection(connection))
            {
                //sqlConnection.Open();

                SqlQuery = "Web_MainFormSearch";

                var p = new DynamicParameters();
                p.Add("@SearchTerm", "Ray Stantz");
                p.Add("@SearchGhost", true);
                p.Add("@SearchVehicles", true);
                //p.Add("@RetVal", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

                fav = sqlConnection.Query<SearchTime>(SqlQuery, p, commandType: CommandType.StoredProcedure).First();
            }

            stopwatch.Stop();
            int differ = (int)stopwatch.ElapsedMilliseconds;

            //Asserts
            Assert.Greater(fav.SearchName.Length, 1);
            Assert.Greater(fav.GroupType.Length, 1);
            //Assert.Greater(1200, differ);
        }
开发者ID:datachomp,项目名称:Ghostbusters,代码行数:33,代码来源:MenuTest.cs


示例17: ScoreManageInfo_Add

 public static ScoreManageInfo ScoreManageInfo_Add(ScoreManageInfo model)
 {
     try
     {
         using (var conn = DbHelper.CCService())
         {
             var p = new DynamicParameters();
             p.Add("@output", dbType: DbType.Int32, direction: ParameterDirection.Output);
             p.Add("@OCID", model.OCID);
             p.Add("@UserID", model.UserID);
             p.Add("@UserName", model.UserName);
             p.Add("@CourseID", model.CourseID);
             p.Add("@StartDate", model.StartDate);
             p.Add("@EndDate", model.EndDate);
             p.Add("@Name", model.Name);
             p.Add("@ScoreTypeID", model.ScoreTypeID);
             conn.Execute("Score_Test_ADD", p, commandType: CommandType.StoredProcedure);
             model.TestID = p.Get<int>("output");
             return model;
         }
     }
     catch (Exception e)
     {
         return null;
     }
 }
开发者ID:holdbase,项目名称:IES2,代码行数:26,代码来源:ScoreManageInfoDAL.cs


示例18: CanAddPlaylist

        public bool CanAddPlaylist(int userId)
        {
            try
            {
                
                using (var smartTimer = new SmartTimer((x, u) => GatewayLoggerInfo("Exit CanAddPlaylist", userId, x.Elapsed)))
                {
                    GatewayLoggerInfo("CanAddPlaylist", userId);
                    using (var connection = _provider.Create())
                    {
                        var parameters = new DynamicParameters();
                        parameters.Add("@userId", userId);
                        parameters.Add("@canAdd", dbType: DbType.Boolean, direction: ParameterDirection.Output);

                        connection.Execute("user.CanAddPlaylist", parameters, commandType: CommandType.StoredProcedure);

                        return parameters.Get<bool>("@canAdd");
                    }
                }
            }
            catch (System.Exception ex)
            {
                logger.Error(ex);
                throw;
            }
        }
开发者ID:dublow,项目名称:MagicPlaylist,代码行数:26,代码来源:MagicPlaylistGateway.cs


示例19: Dispose

        public void Dispose()
        {
            if (_completed) return;

            _completed = true;

            var parameters = new DynamicParameters();
            parameters.Add("@Resource", _resource);
            parameters.Add("@LockOwner", LockOwner);
            parameters.Add("@Result", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

            _connection.Execute(
                @"sp_releaseapplock",
                parameters,
                commandType: CommandType.StoredProcedure);

            var releaseResult = parameters.Get<int>("@Result");

            if (releaseResult < 0)
            {
                throw new SqlServerDistributedLockException(
                    String.Format(
                        "Could not release a lock on the resource '{0}': Server returned the '{1}' error.", 
                        _resource,
                        releaseResult));
            }
        }
开发者ID:henningst,项目名称:HangFire,代码行数:27,代码来源:SqlServerDistributedLock.cs


示例20: UploadExcelFromSqlToDropBox

        public void UploadExcelFromSqlToDropBox(string savedQuery, string sqlscript, string targetpath, string filename)
        {
            using (var db2 = NewDataContext())
            {
                var accesstoken = db2.Setting("DropBoxAccessToken", ConfigurationManager.AppSettings["DropBoxAccessToken"]);
                var script = db2.Content(sqlscript, "");
                if (!script.HasValue())
                    throw new Exception("no sql script found");

                var p = new DynamicParameters();
                foreach (var kv in dictionary)
                    p.Add("@" + kv.Key, kv.Value);
                if (script.Contains("@qtagid"))
                {
                    int? qtagid = null;
                    if (savedQuery.HasValue())
                    {
                        var q = db2.PeopleQuery2(savedQuery);
                        var tag = db2.PopulateSpecialTag(q, DbUtil.TagTypeId_Query);
                        qtagid = tag.Id;
                    }
                    p.Add("@qtagid", qtagid);
                }
                var bytes = db2.Connection.ExecuteReader(script, p).ToExcelBytes(filename);

                var wc = new WebClient();
                wc.Headers.Add($"Authorization: Bearer {accesstoken}");
                wc.Headers.Add("Content-Type: application/octet-stream");
                wc.Headers.Add([email protected]"Dropbox-API-Arg: {{""path"":""{targetpath}/{filename}"",""mode"":""overwrite""}}");
                wc.UploadData("https://content.dropboxapi.com/2-beta-2/files/upload", bytes);
            }
        }
开发者ID:GSBCfamily,项目名称:bvcms,代码行数:32,代码来源:Upload.cs



注:本文中的Dapper.DynamicParameters类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# DarkMultiPlayerCommon.ClientMessage类代码示例发布时间:2022-05-24
下一篇:
C# UserInterface.BaseScreenComponent类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap