I have a WPF application in which I'm trying to use Entity Framework 4.1 Code First for Data Access Logic. I'm using MySQL as DBMS. For simplicity I have created just one data class User:
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[Required]
[MaxLength(50)]
public string Surname { get; set; }
[Required]
[MaxLength(50)]
public string Username { get; set; }
[Required]
[MaxLength(255)]
public string Password { get; set; }
}
And I have an ApplicationContext class extending the DbContext like:
public class ApplicationContext : DbContext
{
public ApplicationContext()
: base()
{
}
public DbSet<User> Users;
}
I add a connection string with the name ApplicationContext
to the app.config
file.
<configuration>
<connectionStrings>
<clear/>
<add name="ApplicationContext"
connectionString="server=localhost;User Id=myuser;Password=mypassword;Persist Security Info=True;database=mydatabase"
providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Da开发者_开发问答ta.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient"
description=".Net Framework Data Provider for MySQL"
type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.4.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
</configuration>
And when I try to initialize the database with the following code inside the App.xaml.cs
file OnStartup
method, I get ProviderIncompatibleException
saying The provider did not return a ProviderManifestToken string.
And the inner exception says Unknown database
.
Database.SetInitializer<ApplicationContext>(
new DropCreateDatabaseIfModelChanges<ApplicationContext>());
this.AppDatabaseContext = new ApplicationContext();
this.AppDatabaseContext.Database.Initialize(true);
I think it tries to connect to the database with the database name I have provided in the connection string and fails since it does not exist. However, I expect that it should create one if there isn't already.
I also tried to create the database by hand from MySQL and re-run the application, this time I get a different type of exception: NotSupportedException
saying Model compatibility cannot be checked because the database does not contain model metadata. Ensure that IncludeMetadataConvention has been added to the DbModelBuilder conventions
I have searched the internet and tried many things to overcome this problem but couldn't find a solution.
Any help will be greatly appreciated.
It could be a problem with the version of the ado.net provider for MySQL that you are using.
The latest version of dotconnect for MySQL supports code-first for EF 4.1, see http://www.devart.com/news/2011/dotconnects630.html
精彩评论