我错过了数据库的这些错误

问题描述 投票:-4回答:1

我错过了这些错误:

System.ArgumentException: Keyword not supported: 'initial catalog'.
   at System.Data.SqlServerCe.SqlCeConnectionStringBuilder.GetIndex(String keyword)
   at System.Data.SqlServerCe.SqlCeConnectionStringBuilder.set_Item(String keyword, Object value)
   at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value)
   at System.Data.SqlServerCe.SqlCeConnectionStringBuilder..ctor(String connectionString)
   at System.Data.SqlServerCe.SqlCeConnection.set_ConnectionString(String value)
   at System.Data.SqlServerCe.SqlCeConnection..ctor(String connectionString)
   at Task5.Data.SqlRepository`1.GetTable(String where) in D:\Task5\Task5.Data\Repositories\SqlRepository.cs:line 96
   at Task5.Data.SqlRepository`1.Select() in D:\Task5\Task5.Data\Repositories\SqlRepository.cs:line 39
   at Task5.Data.Services.EntityDataService.CategoryList() in D:\Task5\Task5.Data\Services\EntityDataService.cs:line 32
   at Task5.Program.Step1() in D:\Task5\Task5\Program.cs:line 74

我的代码错误:

private List<TEntity> GetTable(string where = null)
{
    var query = $"select * from {GetTableName()} {where}";

    var dataTable = new DataTable();
    using(var sqlConnection = new SqlCeConnection(connectionString))
    {
        SqlCeDataAdapter sqlDA = new SqlCeDataAdapter(query, sqlConnection);
        sqlDA.Fill(dataTable);
    }

    var entityList = new List<TEntity>();
    foreach (DataRow row in dataTable.Rows)
    {
        var entity = new TEntity();
        foreach (DataColumn column in dataTable.Columns)
        {
            var value = row[column.ColumnName];
            typeof(TEntity).GetProperty(column.ColumnName).SetValue(entity, value);
        }

        entityList.Add(entity);
    }

    return entityList;
 }
c# sql-server-ce
1个回答
1
投票

正如@Amy指出的那样,错误信息非常简单。这看起来像是连接字符串的问题,因为您可能尝试将SQL Server连接字符串与SQL CE数据库一起使用。我相信格式应该是这样的:

Data Source=MyData.sdf;Persist Security Info=False;

有关SQL CE连接字符串的更多详细信息,请参阅this link

编辑

如果您实际上正在使用SQL数据库(Express或其他),那么您使用错误的库来连接它。您正在使用不支持SQL Express连接字符串的SqlCeConnection。你应该使用SqlConnectionSqlDataAdapter

注意:我编辑了这个没有经过测试

private List<TEntity> GetTable(string where = null)
{
    var query = $"select * from {GetTableName()} {where}";

    var dataTable = new DataTable();
    using(var sqlConnection = new SqlConnection(connectionString))
    {
        SqlDataAdapter sqlDA = new SqlDataAdapter(query, sqlConnection);
        sqlDA.Fill(dataTable);
    }

    var entityList = new List<TEntity>();
    foreach (DataRow row in dataTable.Rows)
    {
        var entity = new TEntity();
        foreach (DataColumn column in dataTable.Columns)
        {
            var value = row[column.ColumnName];
            typeof(TEntity).GetProperty(column.ColumnName).SetValue(entity, value);
        }

        entityList.Add(entity);
    }

    return entityList;
 }
© www.soinside.com 2019 - 2024. All rights reserved.