Simple Code First Example:

Let's assume that we want to create a simple application for XYZ School. Users of this School application should be able to add or update Students, Standard (Grade), Teacher, and Course information.

Instead of designing database tables first, let's start creating classes for our school domain, as and when needed. First, we will create two simple Student and Standard classes where every Student is associated with one Standard as shown below.

public class Student
{
public Student()
{ }
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime? DateOfBirth { get; set; }
public byte[] Photo { get; set; }
public decimal Height { get; set; }
public float Weight { get; set; } public Standard Standard { get; set; }
}

The Standard (Grade) class should be able to accommodate multiple Students as shown below.

public class Standard
{
public Standard()
{ }
public int StandardId { get; set; }
public string StandardName { get; set; } public ICollection<Student> Students { get; set; } }

Now, we are done with the initial domain classes for our school application. Code-First approach also requires context class which should be derived from DbContext as we have created in the basic tutorials section using Database-First approach. Visit DbContext for more information.

Create a context class as shown below, which derives from DBContext class and exposes DbSet properties for the types that you want to be part of the model, e.g. Student and Standard class, in this case. DbSet is a collection of entity classes (aka entity set), so we have given property name as plural of entity name like Students and Standards.

namespace EF_Code_First_Tutorials
{ public class SchoolContext: DbContext
{
public SchoolContext(): base()
{ } public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; } }
}

Now, we are done with the required classes for the code-first approach. We will now add student using context class as shown below.

class Program
{
static void Main(string[] args)
{ using (var ctx = new SchoolContext())
{
Student stud = new Student() { StudentName = "New Student" }; ctx.Students.Add(stud);
ctx.SaveChanges();
}
}
}

If you run the application, you will be surprised to see that the application runs successfully and one student is successfully inserted into the database.

But, where is the database and what are the tables and its columns?

This is the beauty of Code-First APIs of Entity Framework. It creates the database based on parameter passed in the base constructor of your context class. Since we have not passed any parameter in the constructor of our context class, it created "EF_Code_First_Tutorials.SchoolContext" database in the local SQLEXPRESS database, as shown below. It also created two tables in this database, Students and Standards tables based on Student and Standard domain classes defined above.

As you can see in the above figure, it has created Students and Standards tables and each table contains columns with appropriate datatype and length. The column names and datatype matches with the properties of the respective domain classes. It has also made StudentId and StandardId as PK (primary key) and Standard_StandardId column as FK (foreign key).

This way, without creating a database first, you can start writing an application that will eventually create the database from your domain classes.

You must be wondering how it has created columns with appropriate datatypes and lengh with PK & FK, right? The answer is, using code-first conventions.

Learn code-first conventions in the next section.

Entity Framework Code-First(4):Simple Code First Example的更多相关文章

  1. Entity Framework Tutorial Basics(1):Introduction

    以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...

  2. Entity Framework Tutorial Basics(11):Code First

    Code First development with Entity Framework: Entity Framework supports three different development ...

  3. Entity Framework Tutorial Basics(37):Lazy Loading

    Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means ...

  4. Entity Framework Tutorial Basics(36):Eager Loading

    Eager Loading: Eager loading is the process whereby a query for one type of entity also loads relate ...

  5. Entity Framework Tutorial Basics(32):Enum Support

    Enum in Entity Framework: You can now have an Enum in Entity Framework 5.0 onwards. EF 5 should targ ...

  6. Entity Framework Tutorial Basics(29):Stored Procedure in Entity Framework

    Stored Procedure in Entity Framework: Entity Framework has the ability to automatically build native ...

  7. Entity Framework Tutorial Basics(28):Concurrency

    Concurrency in Entity Framework: Entity Framework supports Optimistic Concurrency by default. In the ...

  8. Entity Framework Tutorial Basics(27):Update Entity Graph

    Update Entity Graph using DbContext: Updating an entity graph in disconnected scenario is a complex ...

  9. Entity Framework Tutorial Basics(22):Disconnected Entities

    Disconnected Entities: Before we see how to perform CRUD operation on disconnected entity graph, let ...

随机推荐

  1. PHP操作MySQL事务处理

    PHP操作MySQL事务处理 /*************** 用begin,rollback,commit来实现 ***************/ /*方法二*/ $conn = mysqli_co ...

  2. TCP/IP 协议中的编址

    TCP/IP协议的互联网需要用到四个级别的地址:物理地址.逻辑地址.端口地址和特定应用地址 一.物理地址 物理地址称为链路地址,是由接点所在的局域网或广域网为该结点指定的地址. 这种地址的长度和格式随 ...

  3. 英语发音规则---L字母

    英语发音规则---L字母 一.总结 一句话总结:[l]音在词首和词尾的发音不同,/l/+其它音节./l/+元音./l/+/j/称它为清晰/l/,发清晰/l/音时,在下一个音即将出出时舌头离开上齿龈,迅 ...

  4. 代码题(1)—lower_bound和upper_bound算法

    1.lower_bound:查找序列中的第一个出现的值大于等于val的位置 这个序列中可能会有很多重复的元素,也可能所有的元素都相同,为了充分考虑这种边界条件,STL中的lower_bound算法总体 ...

  5. css 多行文本以...代替

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  6. php 冒泡排序原理

    $start = microtime(true);   $popArr = array(6,3,23,1,5,100,399,99,66);   echo '6,3,23,1,5,100,399,99 ...

  7. 数据库中的id不会自动 替换,这个应该处理吗。怎么处理,那个是唯一主键

  8. linux命令学习笔记(35):ln 命令

    ln是linux中又一个非常重要命令,它的功能是为某一个文件在另外一个位置建立一个同步的链接.当我们需要在 不同的目录,用到相同的文件时,我们不需要在每一个需要的目录下都放一个必须相同的文件,我们只要 ...

  9. 机器学习 Support Vector Machines 1

    引言 这一讲及接下来的几讲,我们要介绍supervised learning 算法中最好的算法之一:Support Vector Machines (SVM,支持向量机).为了介绍支持向量机,我们先讨 ...

  10. 【遍历二叉树】11把二叉树转换成前序遍历的链表【Flatten Binary Tree to Linked List】

    本质上是二叉树的root->right->left遍历. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ...