Exemplo n.º 1
0
        public async Task <string> GetThumbnail(int id, Stream strm)
        {
            string fileName = string.Empty;

            try
            {
                TransactionOptions topts = new TransactionOptions()
                {
                    Timeout = TimeSpan.FromSeconds(60), IsolationLevel = IsolationLevel.Serializable
                };
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, topts, TransactionScopeAsyncFlowOption.Enabled))
                    using (System.Data.Common.DbConnection conn = _connectionFactory.GetRIAppDemoConnection())
                    {
                        DbContextOptionsBuilder <AdventureWorksLT2012Context> dbOptionsBuilder = new DbContextOptionsBuilder <AdventureWorksLT2012Context>();
                        dbOptionsBuilder.UseSqlServer(conn);
                        // Create in the same transaction and connection!!!
                        using (AdventureWorksLT2012Context db = new AdventureWorksLT2012Context(dbOptionsBuilder.Options))
                        {
                            fileName = await db.Product.Where(a => a.ProductId == id).Select(a => a.ThumbnailPhotoFileName).FirstOrDefaultAsync();

                            if (string.IsNullOrEmpty(fileName))
                            {
                                throw new Exception($"Product: {id} is not found");
                            }

                            using (BlobStream bstrm = new BlobStream(conn as SqlConnection, "[SalesLT].[Product]", "ThumbNailPhoto",
                                                                     string.Format("WHERE [ProductID]={0}", id)))
                            {
                                bstrm.Open();
                                await bstrm.CopyToAsync(strm, 512 * 1024);
                            }

                            scope.Complete();
                        }
                    }

                return(fileName);
            }
            catch (Exception ex)
            {
                string msg = "";
                if (ex != null)
                {
                    msg = ex.GetFullMessage();
                }

                _logger.LogError(ex, msg);
                throw;
            }
        }