关于.net mvc ef6连接mysql时遇到的坑:
- 手写模型类
[Table("user")]
public class UserModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string pwd { get; set; }
}
- 根据添加controller,添加模型上下文(自动生成)
- mysql --version == 5.xxx版本
注意:nuget安装依赖包为mysql.data.entities
版本为6.xx
web.config修改连接字符串,修改EntityFramework配置
<connectionStrings>
<!--web.config mysql连接串-->
<add name="WebEntityContext" connectionString="server=localhost; port=3306; user=root; password=123456; database=aspdb;SslMode=none;" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
<entityFramework>
<!--mysql-->
<defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6" />
<providers>
<!--<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>-->
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"></provider>
</providers>
</entityFramework>
-
mysql --version == 8.xxx
注意:nuget依赖包为:
mysql.Data
|mysql.data.entityframework
两者版本需与自身数据库版本保持一致web.config修改的配置:
<connectionStrings> <!--web.config mysql连接串--> <add name="UserContext" connectionString="server=localhost; port=3306; user=root; password=123456; database=aspdb;SslMode=none;" providerName="MySql.Data.MySqlClient" /> </connectionStrings> <entityFramework> <!--mysql--> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework"></provider> </providers> </entityFramework> <system.data> <DbProviderFactories> <remove invariant="MySql.Data.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=8.0.31.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" /> </DbProviderFactories> </system.data>