先搞清基本概念
CodeFirst、ModelFirst、DbFirst分别代表什么含义
Database First
If you already have a database, the Entity Framework designer built into Visual Studio can automatically generate a data model that consists of classes and properties that correspond to existing database objects such as tables and columns. The information about your database structure (store schema), your data model (conceptual model), and the mapping between them is stored in XML in an .edmx file. The Entity Framework designer provides a graphical UI that you can use to display and edit the .edmx file.
Model First
If you don't have a database yet, you can begin by creating a model in an .edmx file by using the Entity Framework graphical designer in Visual Studio. When the model is finished, the Entity Framework designer can generate DDL (data definition language) statements to create the database. As in Database First, the .edmx file stores model and mapping information.
Code First
Whether you have an existing database or not, you can use the Entity Framework without using the designer or an .edmx file. If you don't have a database, you can code your own classes and properties that correspond to tables and columns. If you do have a database, Entity Framework tools can generate the classes and properties that correspond to existing tables and columns. The mapping between the store schema and the conceptual model represented by your code is handled by convention and by a special mapping API. If you let Code First create the database, you can use Code First Migrations to automate the process of deploying the database to production. Migrations can also automate the deployment of database schema changes to production when your data model changes.
Choose Code First for new development unless you want to use a graphical designer to model database objects and relationships. The Entity Framework designer only works with Database First and Model First. Before you choose Database First or Model First, however, consider how you want to handle updates to the data model after you create the database, and how you want to deploy the database and deploy updates to it. Code First Migrations automates the process of implementing and deploying database schema changes that result from data model changes. The advantages of Code First Migrations might outweigh the advantages of the Entity Framework designer.
CodeFirst为例:
-
定义模型
public class Blog
{
public int Id { get; set; }
public string Content { get; set; }
public virtual Poster poster { get; set; }
}public class Poster
{
public int Id { get; set; }
public string name { get; set; }
public virtual List<Blog> blogs { get; set; }
}
注意模型定义中的virtual,意味延迟加载。延迟加载意味着,尝试访问这些属性的内容时,将自动从数据库加载
定义模型上下文
public class BlogContext : DbContext
{
public DbSet<Blog> blogs { get; set; }
public DbSet<Poster> posters { get; set; }
}
That‘s All!-
操作数据
using (BlogContext con = new BlogContext())
{
con.posters.Add(new Poster { name = "test1"});
con.blogs.Add(new Blog() { Content="MyBlog"});
con.SaveChanges();var query = from b in con.posters orderby b.Id select b; foreach (var item in query) { Console.WriteLine(item); } Console.ReadKey(); }
我的数据在哪?
按照约定,DbContext 已经创建了一个数据库。
如果本地 SQL Express 实例可用(默认情况下随 Visual Studio 2010 安装),则 Code First 已对该实例创建了数据库
如果 SQL Express 不可用,则 Code First 将尝试使用 LocalDb(默认情况下随 Visual Studio 2012 安装)
数据库以派生上下文的完全限定名命名,在我们的示例中,名称为 CodeFirstNewDatabaseSample.BlogContext
可以使用服务器资源管理器连接不同种类数据库
更改模型(数据迁移)
如果在生成数据库后,尝试改变数据定义(Model)则会报错,此时需要进行数据迁移
步骤如下:
1 “工具”->“库程序包管理器”->“程序包管理器控制台”****
2 在程序包管理器控制台中运行 Enable-Migrations 命令
3 在程序包管理器控制台中运行 Add-Migration + 随便起个名字
4 在程序包管理器控制台中运行 Update-Database
这样每次模型变化都会反映到数据库里(每次修改模型都要重新进行3,4步骤)
DataAnnotation 和 Fluent API
使用DataAnnotation
using System.ComponentModel.DataAnnotations;
EF 支持的完整注释列表为:
KeyAttribute
StringLengthAttribute
MaxLengthAttribute
ConcurrencyCheckAttribute
RequiredAttribute
TimestampAttribute
ComplexTypeAttribute
ColumnAttribute
TableAttribute
InversePropertyAttribute
ForeignKeyAttribute
DatabaseGeneratedAttribute
NotMappedAttribute