2010-05-11 3 views
2

Я использую базу данных SQLite и Entity Framework (с .net framework 3.5). Я пытаюсь выполнить простую команду SQL без запроса для создания новой таблицы в этой базе данных. My Entity Framework уже содержит объектную модель для этой таблицы: я просто хочу сгенерировать соответствующую таблицу с помощью команды.Выполнение команды SQlite с инфраструктурой Entity Framework

(Кстати, есть, может быть, лучший способ сделать это. Любые идеи, кто-то :)

Моя проблема заключается в том, что я не в состоянии выполнить любую команду, даже простые команды.

Вот мой код:

EntityConnection entityConnection = new EntityConnection(entitiesConnectionString); 
Entities db = new Entities(entityConnection); 

DbCommand command = db.Connection.CreateCommand(); 
command.CommandText ="CREATE TABLE MyTable (Id int NOT NULL, OtherTable_Id nchar(40)   REFERENCES OtherTable (Id) On Delete CASCADE On Update NO ACTION, SomeData nvarchar(1024) NOT NULL, Primary Key(Id));"; 
command.ExecuteNonQuery(); 

Я получил эту ошибку:

System.Data.EntitySqlException: The query syntax is not valid., near identifier 'TABLE', line 1, column 8. 
    at System.Data.Common.EntitySql.CqlParser.yyerror(String s) 
    at System.Data.Common.EntitySql.CqlParser.yyparse() 
    at System.Data.Common.EntitySql.CqlParser.Parse(String query) 
    at System.Data.Common.EntitySql.CqlQuery.Parse(String query, ParserOptions parserOptions) 
    at System.Data.Common.EntitySql.CqlQuery.Compile(String query, Perspective perspective, ParserOptions parserOptions, Dictionary`2 parameters, Dictionary`2 variables, Boolean validateTree) 
    at System.Data.EntityClient.EntityCommand.MakeCommandTree() 
    at System.Data.EntityClient.EntityCommand.CreateCommandDefinition() 
    at System.Data.EntityClient.EntityCommand.TryGetEntityCommandDefinitionFromQueryCache(EntityCommandDefinition& entityCommandDefinition) 
    at System.Data.EntityClient.EntityCommand.GetCommandDefinition() 
    at System.Data.EntityClient.EntityCommand.InnerPrepare() 
    at System.Data.EntityClient.EntityCommand.ExecuteReader(CommandBehavior behavior) 
    at System.Data.EntityClient.EntityCommand.ExecuteScalar[T_Result](Func`2 resultSelector) 

Это, как представляется, ошибка синтаксиса, но я не могу понять, где проблема и как решить Это. СутьConnection в порядке, потому что я могу использовать любые сущности, сгенерированные с EF.

Я попытался с другой простой командой, но бросить еще одно исключение:

DbCommand command = db.Connection.CreateCommand(); 
command.CommandText = "SELECT COUNT(Id) From OtherTable;"; 
int result = (int)command.ExecuteScalar(); 

И я получил эту ошибку, ведьма не то же самое, но может помочь:

System.Data.EntitySqlException: 'Groupe' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly., near simple identifier, line 1, column 23. 
    at System.Data.Common.EntitySql.CqlErrorHelper.ReportIdentifierError(Expr expr, SemanticResolver sr) 
    at System.Data.Common.EntitySql.SemanticAnalyzer.ConvertIdentifier(Expr expr, SemanticResolver sr) 
    at System.Data.Common.EntitySql.SemanticAnalyzer.Convert(Expr astExpr, SemanticResolver sr) 
    at System.Data.Common.EntitySql.SemanticAnalyzer.ProcessAliasedFromClauseItem(AliasExpr aliasedExpr, SemanticResolver sr) 
    at System.Data.Common.EntitySql.SemanticAnalyzer.ProcessFromClauseItem(FromClauseItem fromClauseItem, SemanticResolver sr) 
    at System.Data.Common.EntitySql.SemanticAnalyzer.ProcessFromClause(FromClause fromClause, SemanticResolver sr) 
    at System.Data.Common.EntitySql.SemanticAnalyzer.ConvertQuery(Expr expr, SemanticResolver sr) 
    at System.Data.Common.EntitySql.SemanticAnalyzer.Convert(Expr astExpr, SemanticResolver sr) 
    at System.Data.Common.EntitySql.SemanticAnalyzer.ConvertRootExpression(Expr astExpr, SemanticResolver sr) 
    at System.Data.Common.EntitySql.SemanticAnalyzer.ConvertGeneralExpression(Expr astExpr, SemanticResolver sr) 
    at System.Data.Common.EntitySql.CqlQuery.AnalyzeSemantics(Expr astExpr, Perspective perspective, ParserOptions parserOptions, Dictionary`2 parameters, Dictionary`2 variables) 
    at System.Data.Common.EntitySql.CqlQuery.Compile(String query, Perspective perspective, ParserOptions parserOptions, Dictionary`2 parameters, Dictionary`2 variables, Boolean validateTree) 
    at System.Data.EntityClient.EntityCommand.MakeCommandTree() 
    at System.Data.EntityClient.EntityCommand.CreateCommandDefinition() 
    at System.Data.EntityClient.EntityCommand.TryGetEntityCommandDefinitionFromQueryCache(EntityCommandDefinition& entityCommandDefinition) 
    at System.Data.EntityClient.EntityCommand.GetCommandDefinition() 
    at System.Data.EntityClient.EntityCommand.InnerPrepare() 
    at System.Data.EntityClient.EntityCommand.ExecuteReader(CommandBehavior behavior) 
    at System.Data.EntityClient.EntityCommand.ExecuteScalar[T_Result](Func`2 resultSelector) 

ответ

2

Я думаю, проблема может заключаться в том, что вы используете EnitityConnection. Вы пробовали использовать OleDbConnection или OdbcDbConnection?

OdbcDbConnection entityConnection = new OdbcDbConnection(entitiesConnectionString); 
Entities db = new Entities(entityConnection); 

DbCommand command = db.Connection.CreateCommand(); 
command.CommandText ="CREATE TABLE MyTable (Id int NOT NULL, OtherTable_Id nchar(40)   REFERENCES OtherTable (Id) On Delete CASCADE On Update NO ACTION, SomeData nvarchar(1024) NOT NULL, Primary Key(Id));"; 
command.ExecuteNonQuery(); 

Там также поставщик ADO.Net для SQLite находится здесь: http://sourceforge.net/projects/sqlite-dotnet2/ Я не использовал его, но он выглядит, как вы могли бы использовать:

SQLiteConnection cnn = new SQLiteConnection(entitiesConnectionString); 
0

Почему ты писать команды SQL в отношении коллекции Entity? Если вы хотите это сделать, используйте компоненты ADO.NET для SQLite, иначе используйте LINQ to Entities для запроса данных из вашей базы данных SQLite.

1

Спасибо за Ваши ответы, вы сохранили мой день :)

Я хотел ограничить количество соединений, и я использовал текущий EntityConnection, чтобы проверить базу данных, прежде чем пытаться ее модифицировать. Но я пробовал этот код, и он отлично работает прямо сейчас:

SQLiteConnection connection = new SQLiteConnection(sqliteConnString); 
connection.Open(); 

DataRow[] result = connection.GetSchema("Tables").Select("Table_Name = 'MyTable'"); 
if (result == null || result.Length == 0) 
{     
    SQLiteCommand cmd = new SQLiteCommand(
         "CREATE TABLE MyTable (Id int NOT NULL, OtherTable_Id nchar(40) REFERENCES OtherTable (Id) On Delete CASCADE On Update NO ACTION, SomeData nvarchar(1024) NOT NULL, Primary Key(Id));" 
    , connection); 

    cmd.ExecuteNonQuery(); 
} 

connection.Close(); 
Смежные вопросы