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. 第二十四篇、socketserver源码剖析

    这里选择的是python2.7(python3和2.7的源码基本类似) #!/usr/bin/env python # -*- coding:utf-8 -*- import SocketServer ...

  2. dhtmlxgrid v3.0学习笔记

    dhtmlxgrid v3.0学习笔记 分类: dhtmlx JavaScript2012-01-31 15:41 1744人阅读 评论(0) 收藏 举报 stylesheetdatecalendar ...

  3. Git 远程仓库 git remote

    http://blog.csdn.net/s0228g0228/article/details/45368155 Git remote -v 查看现有远程仓库的地址url 三种方式都可以. 1. 修改 ...

  4. php中删除数组的第一个元素和最后一个元素的函数

    对于一个php数组,该如何删除该数组的第一个元素或者最后一个元素呢?其实这两个过程都可以通过php自带的函数 array_pop 和 array_shift 来完成,下面就具体介绍一下如何来操作. ( ...

  5. EntityFramework 学习 一 DBEntityEntry

    DbEntityEntry是一个重要的类,用来获取各种各样的实体信息 可以通过DBContext的Entry方法获取DbEntityEntry的实例 DBEntityEntry studentEntr ...

  6. 算法(Algorithms)第4版 练习 1.5.8

    假设原id数组: 0 1 1 4 4 8 6 1 8 0 输入p = 5, q = 7 则输出结果会出错,最终为: 0 1 1 4 4 1 6 1 8 0 因为当id[p](id[5] = 8)被赋值 ...

  7. Tomcat处理HTTP请求源码分析(上)

    Tomcat处理HTTP请求源码分析(上) 作者 张华 发布于 2011年12月8日 | 8 讨论 分享到: 微博 微信 Facebook Twitter 有道云笔记 邮件分享 稍后阅读 我的阅读清单 ...

  8. C语言中的位操作(12)--判断一个数字是否包含一个全零字节

    本文主要介绍一系列算法,算法主要功能是判断一个数字(二进制)中是否包含全零字节 e.g.1010 1111 0000 0000 1001 1111 0001 1111 即 32位整数:A4A3A2A1 ...

  9. HDU 4123 Bob's Race:树的直径 + 单调队列 + st表

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4123 题意: 给你一棵树,n个节点,每条边有长度. 然后有m个询问,每个询问给定一个q值. 设dis[ ...

  10. 通用jquery页面验证

    页面通过给input 标签设置样式或者属性,即可实现所有页面的验证,customValidate方法并支持自己补充验证! 验证包括:必输项,只能输入数字, 输入数字并设定小数最大位数,下拉框必选,复选 ...