CodeFirst是基于Entity Framework的新的开发模式,原先只有Database First和Model First两种。CodeFirst是以代码为中心进行设计的,在具体操作过程中,我们不需要知道数据库的结构。它支持更加优美的开发流程,它允许编写简单的模型对象POCO (plain old classes),而不需要基类。可以通过"约定优于配置",使得数据库持久层不需要任何的配置,也可以覆盖“约定优于配置”,通过流畅的API来完全定制映射。
接下来简单介绍一下CodeFirst的创建流程:
1)先建立控制台程序CodeFirst,创建自己所需要的类:
在此,创建两个简单的类作为演示:Customer类、OrderInfo类。
顾客类:设置Id为主键
<strong>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations; //添加引用
namespace CodeFirst
{
public class Customer
{
[Key]
public int Id { get; set; }
public string CusName { get; set; }
//建立和orderInfo的对应关系,是一对多的关系,所以是一个集合
public virtual ICollection<OrderInfo> order { get; set; }
}
}</strong>
创建订单信息类OrderInfo,设置Id为主键
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace CodeFirest
{
public class OrderInfo
{
[Key] //声明主键
public int Id { get; set; }
public string content { get; set; }
/// <summary>
/// 外键
/// </summary>
public int customerId { get; set; }
public Customer Customer { get; set; }
}
2)需要注意的是,在编码过程中添加所需引用
3)新增Context类:
<strong>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace CodeFirst
{
public class HotelDbContext :DbContext
{
public HotelDbContext()
: base("name=ConnCodeFirst")
{
}
public DbSet<Customer> Customer { get; set; }
public DbSet<OrderInfo> OrderInfo { get; set; }
}
}
</strong>
4)在main方法中写入创建数据库的方法:如果数据库不存在,创建数据库
<strong> static void Main(string[] args)
{
HotelDbContext dbContext = new HotelDbContext();
dbContext.Database.CreateIfNotExists( ); //创建数据库 如果不存在的话
}</strong>
5)添加配置文件:创建连接字符串
<strong><?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings >
<add name="ConnCodeFirst" connectionString="server=192.168.24.99;uid=sa;pwd=123456;database=CodeFirst"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration></strong>
运行后,生成数据库如下:
到此为止,CodeFirst生成数据库就完成了。和另外两种生成方式相比,CodeFirst创建方式更易于维护,至于具体使用哪种方式,还要视情况而定。
------------------------------------