示例#1
0
        public async Task <int> InsertAsync <T>(T entity) where T : class, IEntity, new()
        {
            var entityInfo = MyEntityContainer.Get(typeof(T));

            var sqlBuilder = new SqlServerBuilder();
            var sql        = sqlBuilder.Insert(entityInfo);

            var parameters = new MyDbParameters();

            parameters.Add(entity);

            var command = new SqlCommand(sql);

            command.Parameters.AddRange(parameters.Parameters);

            using (var conn = new SqlConnection(_connectionString))
            {
                conn.Open();
                command.Connection = conn;
                var obj = await command.ExecuteScalarAsync();

                if (obj != DBNull.Value)
                {
                    entity.Id = Convert.ToInt32(obj);
                }
                return(entity.Id);
            }
        }
示例#2
0
        public async Task <int> InsertAsync <T>(List <T> entityList) where T : class, IEntity, new()
        {
            var entityInfo = MyEntityContainer.Get(typeof(T));

            var sqlBuilder = new SqlServerBuilder();
            var sql        = sqlBuilder.Insert(entityInfo);

            var count = 0;

            using (var conn = new SqlConnection(_connectionString))
            {
                conn.Open();
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        foreach (var entity in entityList)
                        {
                            using (var command = new SqlCommand(sql, conn, trans))
                            {
                                var parameters = new MyDbParameters();
                                parameters.Add(entity);
                                command.Parameters.AddRange(parameters.Parameters);
                                var obj = await command.ExecuteScalarAsync();

                                if (obj != DBNull.Value)
                                {
                                    entity.Id = Convert.ToInt32(obj);
                                    count++;
                                }
                            }
                        }
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        count = 0;
                    }
                }
            }

            return(count);
        }