MySql with MVC3 gives an error when calling context.savechanges - mysql

I'm trying to get my MVC3 application to use MySql database instead of Sql Server 2008. I have created the associated database and objects in Mysql. And Updated the connection string in my web.config file to reference MySql.Data.MySqlClient.
When I run my application and try to login, I am getting the error
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
I have a custom MembershipProvider and within the validation process I have the following
using (MyContext context= new MyContext())
{
--some checks here
---
if (verificationSucceeded)
{
user.passwordFailuresSinceLastSuccess = 0;
}
else
{
int failures = user.passwordFailuresSinceLastSuccess;
if (failures != -1)
{
user.passwordFailuresSinceLastSuccess += 1;
user.lastPasswordFailureDate = DateTime.UtcNow;
}
}
context.SaveChanges(); ----THIS IS WHERE IT FALLS OVER
-- some other code here
}
The above code works perfectly well with Sql Server 2008, but is falling over only with MySql. Any idea how I can resolve this please?
I do not have any triggers defined on the underlying table btw. The application is MVC3 with EF Code First.
Thanks,

If anybody else is having this issue, the problem was with the Guid as I though. To get over this, add the following to your connection string
Old Guids=true
So for example, my connection string looks like this now.
<add name="MyDB" connectionString="Server=localhost; Database=mydatabase; Uid=user; Pwd=mypass; Old Guids=true;" providerName="MySql.Data.MySqlClient" />

Related

EF and Code First Migrations with MySQL - dbo.tablename does not exist

I have set up entity framework to use MySQL and created a migration.
When I run update-database I get error "table dbname.dbo.tablename' does not exist. Running in -Verbose mode I see the statement that causes the error :
alter table `dbo.Comments` drop foreign key `FK_dbo.Comments_dbo.Comments_Comment_ID`
When I run the query direct in MySQL workbench is throws the same error.
The problem seems to be the dbo. prefix in the migration set. Anything in the form dbo.tablename won't run saying that table does not exist. E.g. select * from dbo.tablename fails but select * from tablename works. The database was generated by Entity Framework and the code first migrations were generated by EF too.
However the migrations generate everything with the dbo. prefix, which does not work.
Does anyone have a solution to this?
I was having this problem just today as well; found my answer here:
MySqlMigrationCodeGenerator
You have to set:
CodeGenerator = new MySqlMigrationCodeGenerator();
In your context's configuration class. This will get rid of the schema gibberish for MySQL. My Configuration class looks like this:
internal sealed class Configuration : DbMigrationsConfiguration<YourContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
SetSqlGenerator("MySql.Data.MySqlClient", new MySqlMigrationSqlGenerator());
SetHistoryContextFactory("MySql.Data.MySqlClient", (conn, schema) => new MySqlHistoryContext(conn, schema));
CodeGenerator = new MySqlMigrationCodeGenerator();
}
}
I have this same issue and I applied the solution posted by Sorio and It generated a lot of problems.
CodeGenerator = new MySqlMigrationCodeGenerator();
This code line can change all the sql that you generate, for example in my case in the sql code to apply to the database all the foreign key constraints disappear.
I am still without a solution because for me this is not acceptable and I recommend you to check the sql generate with the command before use this solution:
update-database -script

EntityFramework on MySql changing connection string does not change results data

I'm working with EntityFramework 5.0 and MySql. I have generated model from database, and my application now have to connect on multiple database with same structred data.
So i have to dynamic change connection string based on some info.
I try to change database name even from config section of connection string, and with EntityConnectionStringBuilder, but i had the same result: my new connection is stored correctly, but data returned are of the first database.
From WebConfig:
add name="dbIncassiEntities" connectionString="metadata=res:///DAL.Modelincassi.csdl|res:///DAL.Modelincassi.ssdl|res://*/DAL.Modelincassi.msl;provider=Devart.Data.MySql;provider connection string="user id=root ... database=dbname2"" providerName="System.Data.EntityClient" />
From code:
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = providerName;
entityBuilder.ProviderConnectionString = "user id=...database=dbname2";
entityBuilder.Metadata = #"res://*/DAL.Modelincassi.csdl|res://*/DAL.Modelincassi.ssdl|res://*/DAL.Modelincassi.msl";
var context = new dbIncassiEntities(entityBuilder.ToString());
My constructor:
public dbIncassiEntities(string conn)
: base(conn)
{
}
What am i missing?
UPDATE
I can see that calling a query directly from SqlQuery, results returned are correct,
while using the generated entities i retrieve wrong data.
var test = context.Database.SqlQuery<string>(
"SELECT cognomenome FROM addetto limit 0,1").ToList();
But calling..
var oAddetto = from c in context.addettoes select c;
So my problem is only on the model itsself, and manually changing the generated schema
<EntitySet Name="addetto" EntityType="dbIncassiModel.Store.addetto" store:Type="Tables" Schema="dbname2" />
..i'll get the right information.
My question now is: how can i change in code these informations??
Any help is really appreciated!!
Thanks, David
Ok, i've found a workaround for now.
I simply clear the shema name on the designer, and now i can call the generated entities succesfully. Hope this can help anyone else.
David
While I could not remove the Schema in the designer, I removed it directly in the .edmx file. Do a full text search for Schema="YourSchema" in an XML editor of your choice and remove the entries. After that, changing the connection string is enough.
Downside is, the Visual Studio designer and mapping explorer won't work properly anymore.
This seems to be more of a dotConnect issue rather than MySQL, since the problem also exists for the Oracle adapter:
http://forums.devart.com/viewtopic.php?t=17427

SQL Server 2008 - Crash when opening recordset

I have to do some maintenance on a software that was delivered to a customer.
This software is using database and in order to do some debugging session on my computer, I had to install SQL server 2008 R2 and the two database (MyData and MyRecord) that are used by this software.
I had some troubles doing the setting (login, mapping of the database to sa user) but I managed to go over those issues.
Now I am trying to run the software but it crashes during initialization when it tries to open a recordset.
At first I do the following to connect to the database :
::CoInitialize(NULL);
try
{
HRESULT hr = pConnection.CreateInstance("ADODB.Connection");
if (SUCCEEDED(hr))
{
pConnection->ConnectionTimeout = 0;
CString strConnect;
strConnect.Format(_T("Data Source=MyRecord;uid=sa;pwd=sa123456;"));
hr = pConnection->Open((_bstr_t)strConnect,"","", -1);
}
}
with pConnection defined as :
_ConnectionPtr pConnection;
After that, I am trying to read some data from the database "MyRecord" with the following code :
CString sqlQuery = _T("select * from 通道1设置参数表");
try
{
pRecordset.CreateInstance(_uuidof(Recordset));
pRecordset->Open(_bstr_t(sqlQuery ),pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
}
catch(_com_error *e)
{
AfxMessageBox(e->Description());
}
with pRecordSet defined as :
_RecordsetPtr pRecordset;
When the line "pRecordset->Open(...)" is run, the software crashes in the function Recordset15::Open(...) of the msado15.tli file.
In this Recordset15::Open function, the raw_Open(...) function returns DB_E_NOTABLE.
However, I am sure that the table dbo.通道1设置参数表 exists in MyRecord database.
The error is :
I don't know if the problem lies in the SQL server configuration or in the code.
This code works perfectly well on the customer's PC so I would go with a configuration problem.
Thanks in advance !!
In the ODBC connector for this database, the setting "Change the default database to" was not set to the MyRecord database.
I have ticked the check-box, selected the database and now it is working correctly.
Your catch statement should be catch(_com_error & e)
MFC often throws exceptions by pointers, however _com_error is a reference.

Cannot switch a connection string in LLBL Gen Pro

I have two databases with the same schema inside a Sql 2008 R2 Server, of which names are Database1 and Database2. I connected and performed queries on the Database1, and then changed to Database2 to fetch my entities using the following code
this.ConnectionString = "Server=TestServer; Database=Database2;Trusted_Connection=true";
using (IDataAccessAdapter adapter = new DataAccessAdapter(this.ConnectionString))
{
var entities = new EntityCollection<T>();
adapter.FetchEntityCollection(entities, null);
return entities;
}
(The connection string was set before executing the code).
I debugged the application and looked at the value of the connection string, it pointed to the Database2.
However, when I executed the above code, the result was return from the Database1. And if I looked at SQL Profiler, the statement was executed against Database1.
So, could anyone know what was going on? Why the query was executed against the Database1, not Database2.
PS: If I used the above connection string with plain ADO.NET, I was able to retrieve data from Database2.
Thanks in advance.
I have figured out what was going on. The reason was: by default LLBL Gen Pro uses fully qualified names like [database1].[dbo].[Customer] to access database objects, and the catalog is specified when generating entities. So you can't access objects just by changing the connection string.
Hence, to change to another database you have to override the default catalogue by using following code
var adapter= new DataAccessAdapter(ConnectionString, false,
CatalogNameUsage.ForceName, DbName)
{CommandTimeOut = TenMinutesTimeOut};
More information can be found at the following link

Linq with MySQL database in ASP.NET MVC 3, storing DateTime into variable

I am using MySQL database to work in ASP.NET MVC 3, i've already set up all requirements and connection is working fine. This code below is working properly and produce right result :
try
{
ViewBag.Model = (from n in _db.mainDatas
where n.time_stamp == new DateTime(2010, 11, 3, 0, 0, 15)
select n).Take(10).ToList();
}catch (Exception e) {
ViewBag.Error = e;
}
But when i change this code into :
DateTime test = new DateTime(2010,11,3,0,0,15);
try
{
ViewBag.Model = (from n in _db.mainDatas
where n.time_stamp == test
select n).Take(10).ToList();
}catch (Exception e) {
ViewBag.Error = e;
}
this error message is generated :
MySql.Data.MySqlClient.MySqlException: Fatal error encountered during command execution. ---> MySql.Data.MySqlClient.MySqlException: Unable to serialize date/time value
I am using MySQL Connector/Net 6.3.6. Any solution to this problem ?
It seems to be a problem with the Linq to SQL provider for MySql that you have been using.
In first case the date part is "in" the Expression tree that is generate from your linq query where as in the second case the DateTime is declared out side of the Linq query and hence the generated expression tree will be different from the first case. Now it depends on the parser of expression tree in the Linq to SQL provider how to handle both the cases and it seems in this case the provider is not able to properly handle the second case expression tree.
Ok, after doing some searches and googling like crazy, finally I found the solution for my problem. Well, it's not a solution actually, because it looks like MySQL Connector/Net 6.3.6 is not doing well with my project (maybe because of my server, database, project configurations, etc) so I use Devart dotConnector instead of MySQL Connector/Net 6.3.6 and everything works like magic. :D