1 环境
VS2013
MySql
2 使用VS2013新建一个Console工程CodeFirstSample,并使用Nuget安装EntityFramework库及Mysql.Data.Entity相关库。
Install-package EntityFramework –Version 5.0 Install-package Mysql.Data.Entity
3 配置App.config中的连接字符串
<connectionStrings> <add name="BloggingContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=dbCodeFirstSample;user id=root;password=111111" providerName="MySql.Data.MySqlClient"/> </connectionStrings>
4 新建Model及DbContext子类。
Models
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public virtual List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
DbContext子类BloggingContext,用来对存储的Blogs及Posts进行CRUD操作。
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
5 对Console中的Main方法添加测试类,查看是否成功生成相关数据库表。
static void Main(string[] args)
{
using (var db = new BloggingContext())
{
// Create and save a new Blog
Console.Write("Enter a name for a new Blog: ");
var name = Console.ReadLine();
var blog = new Blog { Name = name };
db.Blogs.Add(blog);
db.SaveChanges();
// Display all Blogs from the database
var query = from b in db.Blogs
orderby b.Name
select b;
Console.WriteLine("All blogs in the database:");
foreach (var item in query)
{
Console.WriteLine(item.Name);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
6 按F5运行,并且数据库中已经建立了相应的数据表