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 ...
随机推荐
- 什么是gitlab CI ?CI代表什么?
CI是Continuous Integration的简称,就是持续集成的意思. 就是说你代码改动了,测试了,提交了,持续集成系统会自动构建(编译等等).持续集成的理念是每个提交的版本都应该是可交付的, ...
- ios 微信发送位置
@interface GroupReportViewController () <BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCode ...
- Linux上网设置
ifconfig 命令查看网络设置 步骤1.配置/etc/sysconfig/network-scripts/ifcfg-eth0 里的文件.有的是(ifcfg-ens33) 文件 CentOS下的i ...
- 算法(Algorithms)第4版 练习 2.2.11(1)
实现关键代码: private static void sort(Comparable[] input, int lo, int hi) { if((lo+CUTOFF-1) >= hi) { ...
- css3加载spinner
使用代码制作一个加载旋转器spinner 实现的原理是: 1.两个圆圈,其中一个圆圈是使用pseudo元素(:before)产生 2.由pseudo元素生成的圆通过负数的z-index而作用在下面 3 ...
- 5 Python 数据类型—数字
Python Number 数据类型用于存储数值. 数据类型是不允许改变的,这就意味着如果改变 Number 数据类型的值,将重新分配内存空间. var1 = 1 var2 = 10 您也可以使用de ...
- T62
Forgiveness is the fragrance that the violet sheds on the heel that has crushed it.你一脚踩在紫罗兰上,它却把香味留在 ...
- 关于MFC消息的总结
一.MFC的消息类型 MFC的消息类型大致可以分为三种: 1.命令消息.由菜单和工具栏或快捷键产生,以WM_COMMAND形式发出(以WM_COMMAND发出的还有很多控件,如Button等,但它们产 ...
- bzoj 3653: 谈笑风生 可持久化线段树
题目大意 在一棵单位边权的有根树上支持询问: 给定a,k求满足下列条件的有序三元对的个数. a,b,c互不相同 a,b均为c的祖先 a,b树上距离<=k 题解 solution 1 首先我们知道 ...
- 使用UIBezierPath添加投影效果
代码: ViewController.h #import <UIKit/UIKit.h> @interface ViewControlle ...