2.简单的Code First例子(EF Code-First系列)
现在假想,我们想要为讴歌学校创建一个应用程序,这个程序需要能够来添加或者更新学生,分数,教师还有课程信息。
代替之前我们的做法:先是创建数据库,现在我们不这么做,我们先来创建领域类,首先我来创建两个简单的类,一个是Student类,一个是Standard类。
每个学生都有一个分数,下面看代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF1
{
public class 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; }
}
}
这个Standard(分数类)需要容纳下复数个学生(Student )
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EF1
{
public class Standard
{
public int StandardId { get; set; }
public string StandardName { get; set; }
public ICollection<Student> Students { get; set; }
}
}
现在,我们已经为我们的程序完成了,领域类初始化的工作。Code-First方法,同样需要一个继承自DbContext的上下文类。了解更多上下文类的信息请点击: DbContext
创建上下文类的代码如下,我们这个上下文类,继承自DbContext类,然后暴露你想要的模型的实体的DbSet属性,例如,Student和Standard类,在这个例子中。DbSet是实体的集合(also konw as entity set),所以我们给这个实体的属性名字是复数的。
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF1
{
public class DbContextClass:DbContext
{
public DbContextClass()
: base()
{ }
public DbSet<Student> Studnets { get; set; }
public DbSet<Standard> Standards { get; set; }
}
}
现在我们已经创建了必须的领域类和上下文类,现在让我们使用上下文,来添加一个学生信息吧
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF1
{
class Program
{
static void Main(string[] args)
{
Student stu = , StudentName = , Weight = ,DateOfBirth=DateTime.Now};
using (var db = new DbContextClass())
{
db.Studnets.Add(stu);
db.SaveChanges();
}
Console.WriteLine("添加成功");
Console.ReadKey();
}
}
}
运行的效果图:

运行成功了?那么你会奇怪,数据库呢,数据表呢,别奇怪,慢慢看:
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.
这就是Code-First APIs的优点,它基于上下文类中的base构造器中的参数,为我们创建了数据库。尽管,我们没有传递任何参数到构造器中,它为我们在这个目录下面【C:\Users\XXXXXX】创建了这个数据库:

注意:因为我的数据库版本不是免费版的,所以创建的数据库,在这个目录下面:【C:\Users\XXXXXX】
现在我想把这个数据库,附加到我的SQL中,查看里面的表,但是出错了:

版本不支持,我数据库的版本是SQL2008,这个数据库的版本,应该是比2008低级的版本。
在网上百度了一下:解决方案地址:http://www.2cto.com/database/201404/294024.html
“数据库 的版本为 661,无法打开。此服务器支持 655 版及更低版本。不支持降级路径”
出现这样的问题,一般是因为数据库版本不同造成的。
我们可以用下面的语句查询数据库的版本
use master
select @@VERSION
(1)661是sql2008 R2的版本号
Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (Intel X86) Apr 2 2010 15:53:02 Copyright (c) Microsoft
(2)655版本也就是sql2008 sp1版本号
Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (Intel X86) Mar 29 2009 10:27:29 Copyright (c) 1988-2008
如果后面是1600,则表明只安装了sql2008r2,还要装一个sql2008sp1。这样才能保证后面是2500.
刚好我的数据库,是第一个版本。我来找一个SQL2008Sp1。
这个还是不行,需要安装SQL2012。。。。。。
自己也懒得安装SQL2012,既然那这种办法不行,那就想起他的办法,现在我们来修改一下,上下文类:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF1
{
public class DbContextClass:DbContext
{
public DbContextClass()
: base("ConnectionString")
{ }
public DbSet<Student> Studnets { get; set; }
public DbSet<Standard> Standards { get; set; }
}
}
然后我们改一下配置文件加上这个节点:
<connectionStrings>
<add name="ConnectionString" connectionString="server=.;database=EFCodeFirstDB;uid=sa;pwd=Password_1" providerName="System.Data.SqlClient"/>
</connectionStrings>
运行程序,成功之后,我们打开数据库。奇迹出现了!
生成了数据库,在SQL2008中:

然后我们打开看里面的表,字段:

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.
你可以看到上面的图片中,创建了数据库和表,并且还有主外键。这些都是Code-First约定帮助我们实现的。
附上系列目录:
- 什么是Code First
- 简单的Code First例子
- Code-First 约定
- DB Initialization(数据库初始化)
- Inheritance Strategy(继承策略)
- Configure Domain Classes(配置领域类)
- DataAnnotations(数据注解)
- Fluent API
- Configure One-to-One(配置一对一关系)
- Configure One-to-Many(配置一对多关系)
- Configure Many-to-Many(配置多对多关系)
- Move Configurations(数据迁移)
- DB Initialization Strategy(数据库初始化策略)
- ...待续.....
2.简单的Code First例子(EF Code-First系列)的更多相关文章
- 1.什么是Code First(EF Code First 系列)
EF4.1中开始支持Code First .这种方式在领域设计模式中非常有用.使用Code First模式,你可以专注于领域设计,根据需要,为你一个领域的对象创建类集合,而不是首先来设计数据库,然后来 ...
- EF Code First学习系列
EF Model First在实际工作中基本用不到,前段时间学了一下,大概的了解一下.现在开始学习Code First这种方式.这也是在实际工作中用到最多的方式. 下面先给出一些目录: 1.什么是Co ...
- EF和MVC系列文章导航:EF Code First、DbContext、MVC
对于之前一直使用webForm服务器控件.手写ado.net操作数据库的同学,突然来了EF和MVC,好多新概念泉涌而出,的确犹如当头一棒不知所措.本系列文章可以帮助新手入门并熟练使用EF和MVC,有了 ...
- EF Code First 初体验
Code First 顾名思义就是先代码,再由代码生成数据库的开发方式. 废话不多说,直接来一发看看:在VS2010里新建一个空白解决方案,再依次添加两个类库项目:Model.DataAccess和一 ...
- IoC容器Autofac - Autofac + Asp.net MVC + EF Code First(转载)
转载地址:http://www.cnblogs.com/JustRun1983/archive/2013/03/28/2981645.html 有修改 Autofac通过Controller默认构造 ...
- EF Code First、DbContext
EF Code First.DbContext 对于之前一直使用webForm服务器控件.手写ado.net操作数据库的同学,突然来了EF和MVC,好多新概念一下泉涌而出,犹如当头一棒,的确有点不知所 ...
- 【极力分享】[C#/.NET]Entity Framework(EF) Code First 多对多关系的实体增,删,改,查操作全程详细示例【转载自https://segmentfault.com/a/1190000004152660】
[C#/.NET]Entity Framework(EF) Code First 多对多关系的实体增,删,改,查操作全程详细示例 本文我们来学习一下在Entity Framework中使用Cont ...
- 【记录】EF Code First 实体关联,如何添加、修改实体?
在使用 EF Code First 的时候,我们经常会对项目中的 Entry 进行一对多.多对多的映射配置,这时候就会产生主实体和子实体的概念,我们在添加.修改他们的时候,有时候会产生一些问题,比如添 ...
- EF Code First 一对多、多对多关联,如何加载子集合?
应用场景 先简单描述一下标题的意思:使用 EF Code First 映射配置 Entity 之间的关系,可能是一对多关系,也可能是多对多关系,那如何加载 Entity 下关联的 ICollectio ...
随机推荐
- 分布式数据库中的Paxos 算法
分布式数据库中的Paxos 算法 http://baike.baidu.com/link?url=ChmfvtXRZQl7X1VmRU6ypsmZ4b4MbQX1pelw_VenRLnFpq7rMvY ...
- .NET面试题系列[0] - 写在前面
.NET面试题系列目录 .NET面试题系列[1] - .NET框架基础知识(1) .NET面试题系列[2] - .NET框架基础知识(2) .NET面试题系列[3] - C# 基础知识(1) .NET ...
- 【PRINCE2是什么】PRINCE2认证之七大原则
经过前几讲中关于PRINCE2六大要素,四大步骤及整体思维架构的学习,相信各位看官已经对于PRINCE2有了大概的了解,那我们今天的学习内容会正式进入到七大原则内容的分享. 我们先来回顾一下,PRIN ...
- javascript命名规范
javascript命名规范 3.命名 命名的方法通常有以下几类: a).命名法说明 1).camel命名法,形如thisIsAnApple 2).pascal命名法,形如ThisIsAnApple ...
- SQL Server 跨网段(跨机房)FTP复制
一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 搭建过程(Process) 注意事项(Attention) 参考文献(References) ...
- 配置 L3 agent - 每天5分钟玩转 OpenStack(99)
上一节我们介绍了路由服务(Routing)的基本功能,今天教大家如何配置. Neutron 的路由服务是由 l3 agent 提供的. 除此之外,l3 agent 通过 iptables 提供 fir ...
- Web APi之Web Host消息处理管道(六)
前言 我们知道Web API本身是无法提供请求-响应的机制,它是通过Web Host以及Self Host的寄宿的宿主方式来提供一个请求-响应的运行环境.二者都是将请求和响应抽象成HttpRespon ...
- ListView+CheckBox实现全选 单击效果
在网上也找了一些案例,但都是用Map来实现的.我的是把对象绑定到当前控件上.代码稍微简洁. main布局文件:main.xml <?xml version="1.0" enc ...
- Windows Server 2008 R2 WEB服务器配置系列文章索引
最近这段时间趁天翼云1元主机活动,购买了一个1元主机,主要是为了写一些服务器配置的教程. 已经完成如下几篇文章,送给大家. 国内云主机比较 天翼云/阿里云/腾讯云 Windows Server 200 ...
- MySQL数据库实例参数对比脚本
如何对比两个MySQL实例的参数情况,生产中常会有这样的需求,最近写了个python脚本,可基本实现该需求. 脚本 #!/usr/bin/python import MySQLdb,sys def f ...