上一篇中讲了使用EF—CodeFirst建立项目(SQLServer数据库),这里在篇的基础上将一下MySQL的。
1.建立控制台应用程序CodeFirstByMySQL
2.添加EntityFramework
右击引用——》管理NuGget程序包——》在浏览中搜索EntityFramework——》点击下载安装。
3.添加MySQL相关的MySQL.Data、MySQL.Data.Entity
4.添加类Card、User和数据库上下文CodeFirstByMySQLContext
Card.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstByMySQL.Model
{
public class Card
{
[Key]
public int Id { get; set; }
[StringLength(255)]
public string CardName { get; set; }
}
}
User.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstByMySQL.Model
{
public class User
{
[Key]
public int Id { get; set; }
[StringLength(255)]
public string Name { get; set; }
}
}
CodeFirstByMySQLContext.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstByMySQL.Model
{
public class CodeFirsByMySQLtContext : DbContext
{
//构造函数
public CodeFirsByMySQLtContext()
: base("name = CodeFirstDb")
{
}
public DbSet<User> User { get; set; }
public DbSet<Card> Card { get; set; }
}
}
5.在配置文件App.Config中配置一个数据库连接串,注意providerName="MySql.Data.MySqlClient"
<connectionStrings>
<add name="CodeFirstDb" connectionString="Datasource=localhost;Database=CodeFirstDb;uid=root;pwd=root;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
6.主函数代码:
using CodeFirstByMySQL.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstByMySQL
{
class Program
{
static void Main(string[] args)
{
CodeFirsByMySQLtContext dbcontext = new CodeFirsByMySQLtContext();
User u = new User();
u.Name = "wang";
u.Id = 1;
Card c = new Card();
c.CardName = "lei";
c.Id = 1;
//将实体赋予上下文,并添加到表里
dbcontext.User.Add(u);
//保存
dbcontext.SaveChanges();
}
}
}
6.运行
运行时出现如下问题
解决:需要在配置文件App.Config中的<entityFramwork>节点中添加 codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6",即可解决该问题
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework" >
<parameters>
<parameter value="v13.0" />
</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.Entity.EF6, Version=6.9.12.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
</providers>
</entityFramework>
再次运行便会在MySQL中添加CodeFirstdb数据库,并在users表中添加一条数据