1.安装 Connector/NET 8.0.12 https://dev.mysql.com/downloads/connector/net/
2.创建一个控制台程序,使用NuGet安装 MySql.Data.EntityFramework
3.进入App.config中修改一下配置,这个很鸡贼,你安装的MySql.Data.EntityFramework的版本是Version=8.0.12.0,但是它在App.config里面会生成为Version=8.0.11.0,所以一定要改过来;
4.创建一个数据库上下文,我的创建的是:
class SchoolDBContext : DbContext
{
public SchoolDBContext() : base("name=schooldb")
{
}
public DbSet<Student> Students { get; set; }
}
其中 base(“name=schooldb”) 的意思是找到配置文件中名为“schooldb”的数据库连接字符串:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<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.EntityFramework, Version=8.0.12.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
</provider></providers>
</entityFramework>
<connectionStrings>
<add name="schooldb" connectionString="server=127.0.0.1;port=3306;database=schooldb;uid=root;password=123456;sslmode=none;" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
</configuration>
其中数据库连接字符串要放在最后!!!
5.做完以上4步就可以生成数据库啦,将Main函数替换成下面这个就可以啦,然后点击运行即可在数据库中看到你生成的数据库啦。
class Program
{
static void Main(string[] args)
{
using (var db = new SchoolDBContext())
{
if (db.Database.CreateIfNotExists())
Console.WriteLine("Create DB Success!");
else
Console.WriteLine("DB has already!");
}
Console.ReadLine();
}
}
备注:
打个小广告:专业承接各种项目:客户端、网站、服务端应用;