Entity Framework Code-First(4):Simple Code First Example
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的更多相关文章
- Entity Framework Tutorial Basics(1):Introduction
以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...
- Entity Framework Tutorial Basics(11):Code First
Code First development with Entity Framework: Entity Framework supports three different development ...
- Entity Framework Tutorial Basics(37):Lazy Loading
Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means ...
- 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 ...
- 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 ...
- Entity Framework Tutorial Basics(29):Stored Procedure in Entity Framework
Stored Procedure in Entity Framework: Entity Framework has the ability to automatically build native ...
- Entity Framework Tutorial Basics(28):Concurrency
Concurrency in Entity Framework: Entity Framework supports Optimistic Concurrency by default. In the ...
- Entity Framework Tutorial Basics(27):Update Entity Graph
Update Entity Graph using DbContext: Updating an entity graph in disconnected scenario is a complex ...
- Entity Framework Tutorial Basics(22):Disconnected Entities
Disconnected Entities: Before we see how to perform CRUD operation on disconnected entity graph, let ...
随机推荐
- 手机端适配rem代码片段
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Unity Json解析IPA
今天看到一个unity 自带的解析json的IPA,感觉比litjson好用很多,废话不多,上代码 using System.Collections; using System.Collections ...
- HBase启动后端口60010无法访问
配置好HBase后,想从浏览器通过端口60010看下节点情况,但是提示无法访问 在服务器上netstat -natl|grep 60010 发现并没有60010端口 原来是因为HBase 1.0 之后 ...
- java中的向上转型
Person 可以表示为一个抽象的东西 就是人.比如说人可以唱歌, 就好比Person类中有一个sing方法.那么这个抽象的类(Person 人)可以具体到两类或者更多类 比如 男人,女人 .Man ...
- win2008server R2 x64 部署.net core到IIS
1.下载sdk 和.NET Core Windows Server Hosting https://www.microsoft.com/net/download 2.出现HTTP 错误 500. ...
- 给手机发验证码 综合使用 (忘记密码处理 php发验证码 重置用户密码)
前台页面 提取手机号调用 jQuery的ajax,到发送验证码 [php] view plain copy <title>找回密码 - 2015年xxx报名系统</title> ...
- python自动化开发学习 进程, 线程, 协程
python自动化开发学习 进程, 线程, 协程 前言 在过去单核CPU也可以执行多任务,操作系统轮流让各个任务交替执行,任务1执行0.01秒,切换任务2,任务2执行0.01秒,在切换到任务3,这 ...
- Python入门经典练习题
[程序1] 题目:有1.2.3.4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? num_list=[]cou=0for i in range(1,5): for j in range( ...
- docker 基本概念
image 操作系统 应用 registeries image 的远程仓库 containers 类似一个目录,一个容器包含了 应用运行所需要的一切东西, 容器之间互相独立 image包换一系列的层, ...
- 【论文笔记】基于图机构的推荐系统:Billion-scale Commodity Embedding for E-commerce Recommendation in Alibaba
论文:https://arxiv.org/abs/1803.02349 题外话: 阿里和香港理工联合发布的这篇文章,整体来说,还挺有意思的. 刚开始随便翻翻看看结构图的时候,会觉得:这也能发文章 ...