【问题标题】:'string' does not contain a definition for 'Connection'“字符串”不包含“连接”的定义
【发布时间】:2019-10-06 19:56:44
【问题描述】:

我正在尝试使用 MVC5 中的 Epplus 库和 C# 中的实体框架 6 将文件导入我的 sql 数据库。我收到此错误。我知道我获取连接字符串的方式不对。

我在“连接”上的 await new bulkwriter 行上收到错误

 public async Task<ActionResult> StructureAsync(FormCollection postedFile)
    {
        var usersList = new List<bomStructuredImportTgt>();
        if (Request != null)
        {
            HttpPostedFileBase file = Request.Files["postedFile"];
            if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
            {
                string fileName = file.FileName;
                string fileContentType = file.ContentType;
                byte[] fileBytes = new byte[file.ContentLength];
                var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
                using (var package = new ExcelPackage(file.InputStream))
                {
                    var currentSheet = package.Workbook.Worksheets;
                    var workSheet = currentSheet.First();
                    var noOfCol = workSheet.Dimension.End.Column;
                    var noOfRow = workSheet.Dimension.End.Row;
                    for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
                    {
                        var user = new bomStructuredImportTgt();
                        user.ACTUAL_DATE = Convert.ToDateTime(workSheet.Cells[rowIterator, 1].Value);
                        user.DESCRIPTION = workSheet.Cells[rowIterator, 2].Value?.ToString();
                        user.LEVEL = Convert.ToInt32(workSheet.Cells[rowIterator, 3].Value);
                        user.PARENT_PARTNO = workSheet.Cells[rowIterator, 4].Value?.ToString();
                        user.PART_NO = workSheet.Cells[rowIterator, 5].Value?.ToString();
                        user.PART_NAME = workSheet.Cells[rowIterator, 6].Value?.ToString();
                        user.HNS = workSheet.Cells[rowIterator, 7].Value?.ToString();
                        user.DWGSZ = workSheet.Cells[rowIterator, 8].Value?.ToString();
                        user.PART = workSheet.Cells[rowIterator, 9].Value?.ToString();
                        user.L1QTY = Convert.ToInt32(workSheet.Cells[rowIterator, 10].Value);
                        user.COLORM = workSheet.Cells[rowIterator, 11].Value?.ToString();
                        user.ATTCD = workSheet.Cells[rowIterator, 12].Value?.ToString();
                        user.KD = workSheet.Cells[rowIterator, 13].Value?.ToString();
                        user.SELL = workSheet.Cells[rowIterator, 14].Value?.ToString();
                        user.PL_GROUP = workSheet.Cells[rowIterator, 15].Value?.ToString();
                        user.PL1 = workSheet.Cells[rowIterator, 16].Value?.ToString();
                        user.AT1 = workSheet.Cells[rowIterator, 17].Value?.ToString();
                        user.PL2 = workSheet.Cells[rowIterator, 18].Value?.ToString();
                        user.AT2 = workSheet.Cells[rowIterator, 19].Value?.ToString();
                        user.PL3 = workSheet.Cells[rowIterator, 20].Value?.ToString();
                        user.PLANT = workSheet.Cells[rowIterator, 21].Value?.ToString();
                        user.SHRPCMINMAX = workSheet.Cells[rowIterator, 22].Value?.ToString();
                        usersList.Add(user);
                    }
                }
            }
        }

        using (SqlConnection excelImportDBEntities = new SqlConnection("Dev_Purchasing_New_ModelEntities"))
        {

            await new BulkWriter().InsertAsync(usersList, "bomStructuredImportTgt", excelImportDBEntities.Database.Connection, CancellationToken.None);
        }
        return View("Structure");
    }

  public class BulkWriter
    {
        private static readonly ConcurrentDictionary<Type, SqlBulkCopyColumnMapping[]> ColumnMapping =
            new ConcurrentDictionary<Type, SqlBulkCopyColumnMapping[]>();

        public async Task InsertAsync<T>(IEnumerable<T> items, string bomStructuredImportTgt, SqlConnection excelImportDBEntities,
            CancellationToken cancellationToken)
        {
            using (var bulk = new SqlBulkCopy(excelImportDBEntities))
            using (var reader = ObjectReader.Create(items))
            {
                bulk.DestinationTableName = bomStructuredImportTgt;
                foreach (var colMap in GetColumnMappings<T>())
                    bulk.ColumnMappings.Add(colMap);
                await bulk.WriteToServerAsync(reader, cancellationToken);
            }
        }

        private static IEnumerable<SqlBulkCopyColumnMapping> GetColumnMappings<T>() =>
            ColumnMapping.GetOrAdd(typeof(T),
                type =>
                    type.GetProperties()
                        .Select(p => new SqlBulkCopyColumnMapping(p.Name, p.Name)).ToArray());
    }

我有一个 BulkWriter 类,用于批量复制 sql 中的记录。我想使用这个类来提高我的代码的时间效率。

【问题讨论】:

  • 什么是Dev_Purchasing_New_ModelEntities?如果是web.config中的连接字符串的名称,则应自行检索:ConfigurationManager.ConnectionStrings["Dev_Purchasing_New_ModelEntities"]
  • 是的,它是连接字符串中的名称\
  • 这样吗?使用 (SqlConnection excelImportDBEntities = ConfigurationManager.ConnectionStrings["Dev_Purchasing_New_ModelEntities"]) { 等待新 BulkWriter().InsertAsync(usersList, "bomStructuredImportTgt", excelImportDBEntities.Database.Connection, CancellationToken.None); } 返回视图(“结构”);
  • 至于为什么您会收到该特定错误,excelImportDBEntities.Databasestring 类型。 strings 没有 Connection 属性。
  • 我也试过这样,var conString = ConfigurationManager.ConnectionStrings["Dev_Purchasing_New_ModelEntities"].ConnectionString;使用 (SqlConnection excelImportDBEntities = new SqlConnection(conString)) { await new BulkWriter().InsertAsync(usersList, "bomStructuredImportTgt", ((excelImportDBEntities).Database.Connection), CancellationToken.None); }

标签: c# asp.net-mvc-5 entity-framework-6 epplus sqlconnection


【解决方案1】:

试试这个:

string connectionString = ConfigurationManager.ConnectionStrings["Dev_Purchasing_New_ModelEntities"].ConnectionString;
using (SqlConnection excelImportDBEntities = new SqlConnection(connectionString)){
   ...
}

【讨论】:

  • 字符串 connectionString = ConfigurationManager.ConnectionStrings["Dev_Purchasing_New_ModelEntities"].ConnectionString;使用 (SqlConnection excelImportDBEntities = new SqlConnection(connectionString)) { await new BulkWriter().InsertAsync(usersList, "bomStructuredImportTgt", ((excelImportDBEntities).Database.Connection), CancellationToken.None); }
  • 你试过调试这个吗? connectionString 变量的值是多少?您的配置中有有效的连接字符串吗?
  • 是的,我在 Webconfig 中有一个名为 Dev_Purchasing_New_ModelEntities 的有效连接字符串
【解决方案2】:

由于您的excelImportDBEntities 变量是SqlConnection 类型,因此它具有Database 属性。该属性返回一个 string - 此连接连接到的数据库的名称。当然,您无法从数据库名称中获取.Connection,并且在尝试获取时会出现编译错误。

然后,如何解决它。您的BulkWriterInsertAsync 方法在这里需要SqlConnection 对象,而您已经拥有这个对象excelImportDBEntities。为什么不直接使用呢?替换

await new BulkWriter().InsertAsync(usersList, "bomStructuredImportTgt", excelImportDBEntities.Database.Connection, CancellationToken.None);

await new BulkWriter().InsertAsync(usersList, "bomStructuredImportTgt", excelImportDBEntities, CancellationToken.None);

并且这个错误应该消失了。

另一个问题是,正如其他答案和 cmets 中提到的,您似乎对连接字符串处理不当,在编译和运行代码后会产生错误。

【讨论】:

  • 我现在尝试以这种方式传递我的连接字符串,字符串 connectionString = ConfigurationManager.ConnectionStrings["Dev_Purchasing_New_ModelEntities"].ConnectionString;使用 (SqlConnection excelImportDBEntities = new SqlConnection(connectionString)) { await new BulkWriter().InsertAsync(usersList, "bomStructuredImportTgt", excelImportDBEntities, CancellationToken.None); }
  • 错误现在消失了但是它仍然无法正常工作。谢谢,我会接受这个作为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-07
  • 1970-01-01
  • 1970-01-01
  • 2013-08-18
  • 2018-08-14
  • 2016-12-26
  • 1970-01-01
相关资源
最近更新 更多