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. hbase shell-dml(数据管理指令)

    hbase shell数据管理篇: append count delete deleteall get get_counter get_splits incr put scan truncate tr ...

  2. 解决ul里最后一个li的margin问题

    在html+css布局里ul>li挺常用的,在群里(WEB前端开发 458732443)总有新手问怎么解决li的最后一个margin值的问题.下面介绍一下,大神请不要拍砖. 先看两个demo,你 ...

  3. 启动Hive时报错

    报错信息如下 Logging initialized -bin/lib/hive-common-.jar!/hive-log4j.properties Exception in thread &quo ...

  4. Cocos2d-x中手动构造Json::Value

    由于项目需要Json::Value 不是由服务器传送过来,而是自己手动构造. 带数组的json Json::Value items; for(int i=0,i<2;i++) { items[i ...

  5. Ueditor基础使用

    感谢大家对我这个菜鸟的帮助,这是我第一次用.NET做网站.在这里向大家推荐个百度免费的文本编辑器Ueditor,是.NET版的,在http://ueditor.baidu.com/website/in ...

  6. appium界面元素介绍

    一.主窗口 主页面顶部从左到右依次是: AndroidSettings:android相关的设置 GeneralSettings:全局设置,设置appium相关的内容 DeveloperSetting ...

  7. Java_异常_02_java.lang.NoClassDefFoundError: org/apache/log4j/Level

    总结:解析Json时,除了要导入json-lib-2.2-jdk15.jar外,还要导入: commons-beanutils.jar, commons-httpclient.jar, commons ...

  8. javascript-JQuery样式篇(一)

    轻量级的JavaScript库,核心依然是JavaScript,不仅兼容了CSS3,还兼容了各种浏览器 强大的选择器,完善的事件机制,出色的Ajax封装,丰富的UI 进入官方网站获取最新的版本 htt ...

  9. java事务(一)——事务特性

    事务 什么是事务?事务通俗的讲就是要做的事,在计算机术语中一般指访问或更新数据库中数据的一个工作单元.说起事务,那么就要提到事务的ACID特性,即原子性(atomicity).一致性(consiste ...

  10. 关于c++中char*、char ch[]和string区别

    一.字符串指针: char* ch="hello"; 这里的"hello"是字符串常量,是不可以改变的,即通过ch[0]="s"会编译出错. ...