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. spring装配机制

    spring容器创建bean并通过DI(依赖注入)来协调他们之间的关系,他有三种装配机制: 1. 在XML中显式配置 2. 在Java文件中显式配置 3. 隐式的bean发现机制(组件扫描)和自动装配 ...

  2. <a href

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEnco ...

  3. Spring Cloud之Swagger2 API接口管理

    随着微服务架构体系的发展和应用, 为了前后端能够更好的集成与对接,同时为了项目的方便交付,每个项目都需要提供相应的API文档. 来源:PC端.微信端.H5端.移动端(安卓和IOS端) 传统的API文档 ...

  4. 学习docker可能会用到的参考

    局域网部署Docker--从无到有创建自己的Docker私有仓库 http://lib.csdn.net/base/docker 正在刷(学习)一遍官方文档,上面是一些其他可能用到的资料,是在解决自己 ...

  5. CSS重置 reset.css

    1. [文件] reset.css ~/*------------------------------------------* site:ifnoif.net* Style author:ifnoi ...

  6. java:Map借口及其子类HashMap五,identityHashMap子类

    java:Map借口及其子类HashMap五,identityHashMap子类 了解:identityHashMap子类 一般情况下,标准的Map,是不会有重复的key值得value的,相同的key ...

  7. MVC中URL传多个参数

    1.mvc中url传递多个参数不能直接使用&,会报错(从客户端(&)中检测到有潜在危险的 Request.Path 值) 方法①:使用?---/Home/Index/?id=xxx&a ...

  8. L106 Three things we learned from day one at the World Cup

    Hosts Russia got the World Cup off to a flying start by hammering Saudi Arabia 5-0 in the opening ga ...

  9. linux命令学习笔记(48):watch命令

    watch是一个非常实用的命令,基本所有的Linux发行版都带有这个小工具,如同名字一样,watch可以帮你监测 一个命令的运行结果,省得你一遍遍的手动运行.在Linux下,watch是周期性的执行下 ...

  10. 【跨域】Access-Control-Allow-Origin