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. python作用域和js作用域的比较

    1.python和js一样,作用域链在执行方法之前就已经创建了 # 下面的执行结果就是aa,原因是这点python和js一样,作用域链已经创建了,不会去改变 xo="aa" def ...

  2. 20145229吴姗珊《java程序设计》第2次实验报告

    20145229吴姗珊<java程序设计>第2次实验报告 实验名称 Java面向程序设计,采用TDD的方式设计有关实现复数类Complex. 理解并掌握面向对象三要素:封装.继承.多态. ...

  3. JavaScript的undefined与null、NaN的区别

    Javascript的数据类型 在JavaScript中,有三种住数据类型.两种复合数据类型和两种特殊数据类型. 1.主数据类型(基元数据类型) 字符串 String数据类型: 字符串值是一个由零个或 ...

  4. sql优化,索引学习

  5. java处理json数据

    如果要处理json数据首先要确定使用的json包是那个,常用的有json-lib-x.jar和jack-json-x.jar.我这里的实例代码为json-lib-2.4-jdk15.jar. 在jso ...

  6. java套接字实现接口访问

    是学校博客上的:http://blog.csdn.net/z69183787/article/details/17580325

  7. 纯CSS3跳动焦点广告轮播特效

    1. [代码] 纯CSS3跳动焦点广告轮播特效 <!--  Author: Developed by Caleb Jacob Author Website: http://iamceege.co ...

  8. BZOJ 1059 [ZJOI2007]矩阵游戏:二分图匹配

    题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1059 题意: 给你一个n*n的01矩阵. 你可以任意次地交换某两行或某两列. 问你是否可以 ...

  9. java反射(二)

    java的很多框架都是基于反射的.

  10. node.js定时任务:node-schedule的使用

    安装 npm install node-schedule 使用方法 1:确定时间 例如:2014年2月14日,15:40执行 var schedule = require("node-sch ...