Entity Framework : Set MySQL custom environment variables

可紊 提交于 2019-12-24 22:32:21

问题


I have an issue with Entity Framework 5.0. I'm working with Silverlight 5 and MySQL 5.6 too.

I need to set an environment MySQL variable before each connexion to the MySQL server.

E.g

SET @my_var = 'test';

Under Mysql I don't have any issues.

The following raises an EntityFrameworkException (syntax error near '@').

this.ObjectContext.CreateQuery<object>(" SET @my_var = 'test' ");

OR

this.ObjectContext.CreateQuery<object>(" CALL set_my_var('test') ");

This last method raises a MySQLException saying that a DataReader is already open and need to be closed.

this.ObjectContext.ExecuteStoreQuery<object>(" CALL set_my_var('test') ", null);

I also tried to set a MySQL system environment (no '@') with the same result every time.

Any help will be much appreciated ! Thank you.


回答1:


Since your statement is not a query (i.e. does not return any result) you should use ExecuteStoreCommand. Something like this should work:

ctx.ExecuteStoreCommand("SET @my_var = 'test'")



回答2:


I tried so many things that I misspelled my variable in my code. So the following finaly worked : ctx.ExecuteStoreCommand("SET @my_var = 'test'");

I decided to leave the instruction in the method Initialize of my domain service. This method is inherited of the LinqToEntitiesDomainService class.

But you need to set Allow User Variables=True in your MySQL connection string (ref : Is it possible to use a MySql User Defined Variable in a .NET MySqlCommand?)

You simply need to use a recent version of the MySQL Connector because older versions use the '@' mark to define SQL parameters so it could conflict with custom variables. Now it uses the '?' mark : http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlcommand.html

My library was already up to date (6.6.5).

Thank you for the help !



来源:https://stackoverflow.com/questions/15766530/entity-framework-set-mysql-custom-environment-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!