EF| CodeFirst 代码先行
CodeFirst 实例一
1.新建一个WebForm项目,名字就叫CodeFirstEF
2:在项目中添加引用EF所需要的5个核心类库:(如果找不到这几个类库,可以新建基于数据库的ADO.NET 实体数据模型,然后从里面拷贝)
1. EntityFramework
2. System.Data.Entity
3. System.ComponentModel.DataAnnotations
4. System.Runtime.Serialization
5. System.Security
3:EF需要依赖Web.config配置文件中的三个节点。我需要将这三个节点拷贝到项目的Web.config文件中的<configuration>节点下。这三个节点就是:
- <?xml version="1.0" encoding="utf-8"?>
- <!--
- 有关如何配置 ASP.NET 应用程序的详细信息,请访问
- http://go.microsoft.com/fwlink/?LinkId=169433
- -->
- <configuration>
- <!--要将以下个3节点加入到Web.config文件中来;当然 <system.web>这个节点本身就存在的-->
- <configSections>
- <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
- <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
- </configSections>
- <system.web>
- <compilation debug="true" targetFramework="4.5" />
- <httpRuntime targetFramework="4.5" />
- </system.web>
- <connectionStrings>
- <!--如果从别处拷贝过来的话,这需要将connectionString的值修改成我们自己需要的连接字符串。如果是使用的ADO.NET的话还需要将providerName的值修改成providerName="System.Data.SqlClient"-->
- <add name="ConnStr" connectionString="server=.;database=MySales ;uid=sa;pwd=123456;" providerName="System.Data.SqlClient" />
- </connectionStrings>
- <entityFramework>
- <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
- <parameters>
- <parameter value="v11.0" />
- </parameters>
- </defaultConnectionFactory>
- </entityFramework>
- </configuration>
<?xml version="1.0" encoding="utf-8"?> <!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
http://go.microsoft.com/fwlink/?LinkId=169433
--> <configuration> <!--要将以下个3节点加入到Web.config文件中来;当然 <system.web>这个节点本身就存在的-->
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<connectionStrings>
<!--如果从别处拷贝过来的话,这需要将connectionString的值修改成我们自己需要的连接字符串。如果是使用的ADO.NET的话还需要将providerName的值修改成providerName="System.Data.SqlClient"-->
<add name="ConnStr" connectionString="server=.;database=MySales ;uid=sa;pwd=123456;" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
4.我们想使用EF去访问数据库,就必须要定义一个EF上下文容器类
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Data.Entity; //要想使用DbContext类就必须要引入一个类库
- using CodeFirstEF.Model;
- namespace CodeFirstEF.EFlib
- {
- //BaseDbContext类继承了BaseDbContext类后,它就是一个上下文容器类了
- public class BaseDbContext:DbContext
- {
- //这个类将来要被实例化的,实例化应该初始化ADO.NET的连接字符串,所以这里调用父类一个带参数的构造函数,指明去Web.config文件去<connectionStrings>节点下找到Name为ConnStr的节点值去初始化这个ADO..NET连接字符串
- public BaseDbContext() : base("name=ConnStr")
- {
- //告诉EF容器,如果没有ConnStr连接字符串中配置的数据库,则自动创建这个数据库。(我们ConnStr连接字符串中配置的数据库名字叫MySales,如果我们SQL Server中不存在这个MySales数据库则自动创建这个数据库)
- base.Database.CreateIfNotExists();
- }
- //public DbSet<UserInfo> UserInfo{get;set;} //可建立这个属性,也可以不建立,如果不建立的时候,直接使用db.Set<UserInfo>().Add(model);来增加数据
- }
- }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity; //要想使用DbContext类就必须要引入一个类库
using CodeFirstEF.Model; namespace CodeFirstEF.EFlib
{
//BaseDbContext类继承了BaseDbContext类后,它就是一个上下文容器类了
public class BaseDbContext:DbContext
{
//这个类将来要被实例化的,实例化应该初始化ADO.NET的连接字符串,所以这里调用父类一个带参数的构造函数,指明去Web.config文件去<connectionStrings>节点下找到Name为ConnStr的节点值去初始化这个ADO..NET连接字符串
public BaseDbContext() : base("name=ConnStr")
{
//告诉EF容器,如果没有ConnStr连接字符串中配置的数据库,则自动创建这个数据库。(我们ConnStr连接字符串中配置的数据库名字叫MySales,如果我们SQL Server中不存在这个MySales数据库则自动创建这个数据库)
base.Database.CreateIfNotExists(); } //public DbSet<UserInfo> UserInfo{get;set;} //可建立这个属性,也可以不建立,如果不建立的时候,直接使用db.Set<UserInfo>().Add(model);来增加数据
}
}
现在就可以使用这个EF容器类了
新建一个Web窗体
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- namespace CodeFirstEF
- {
- using CodeFirstEF.EFlib;
- using CodeFirstEF.Model;
- public partial class WebForm1 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- BaseDbContext db = new BaseDbContext();
- UserInfo model = new UserInfo() {UserName = "小肚子", Age = 103 };
- //db.UserInfo.Add(model);//或者采用下面的方式
- db.Set<UserInfo>().Add(model);
- db.SaveChanges();
- }
- }
- }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; namespace CodeFirstEF
{
using CodeFirstEF.EFlib;
using CodeFirstEF.Model;
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
BaseDbContext db = new BaseDbContext(); UserInfo model = new UserInfo() {UserName = "小肚子", Age = 103 }; //db.UserInfo.Add(model);//或者采用下面的方式
db.Set<UserInfo>().Add(model); db.SaveChanges();
}
}
}
然后运行,我们会发现SQL Server中已经生成了MySales这个数据库了。同时下面还生成了一个名字为UserInfo的表。同时表中还插入了一条数据。
----------------------------------------------
CodeFirst 实例二 | 使用三层
下面是最新的做做的一个Demo 使用三层
UI层
WebForm1.aspx
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- namespace WebApp
- {
- using BLL;
- using Models;
- public partial class WebForm1 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- T_UserInfoBll bll = new T_UserInfoBll();
- T_UserInfo user = new T_UserInfo() { Name = "张三丰", Age = 105 };
- bll.AddData(user);
- var b = bll.QueryWhere(r => r.Age > 10);
- this.GridView1.DataSource = b;
- GridView1.DataBind();
- }
- }
- }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; namespace WebApp
{
using BLL;
using Models;
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
T_UserInfoBll bll = new T_UserInfoBll(); T_UserInfo user = new T_UserInfo() { Name = "张三丰", Age = 105 };
bll.AddData(user); var b = bll.QueryWhere(r => r.Age > 10);
this.GridView1.DataSource = b;
GridView1.DataBind();
}
}
}
BLL层
T_UserInfoBll.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace BLL
- {
- using DAL;
- using Models;
- public class T_UserInfoBll
- {
- public List<T_UserInfo> QueryWhere(System.Linq.Expressions.Expression<Func<T_UserInfo, bool>> where)
- {
- T_UserInfoDal dal = new T_UserInfoDal();
- return dal.QueryWhere(where);
- }
- public bool AddData(T_UserInfo model)
- {
- T_UserInfoDal dal = new T_UserInfoDal();
- return dal.AddData(model);
- }
- }
- }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace BLL
{
using DAL;
using Models;
public class T_UserInfoBll
{ public List<T_UserInfo> QueryWhere(System.Linq.Expressions.Expression<Func<T_UserInfo, bool>> where)
{
T_UserInfoDal dal = new T_UserInfoDal();
return dal.QueryWhere(where);
} public bool AddData(T_UserInfo model)
{
T_UserInfoDal dal = new T_UserInfoDal();
return dal.AddData(model);
}
}
}
DAL层
T_UserInfoDal.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace DAL
- {
- using Models;
- public class T_UserInfoDal
- {
- public List<T_UserInfo> QueryWhere(System.Linq.Expressions.Expression<Func<T_UserInfo, bool>> where)
- {
- BaseDbContext db = new BaseDbContext();
- return db.T_UserInfo.Where(where).ToList();
- }
- public bool AddData(T_UserInfo model)
- {
- BaseDbContext db = new BaseDbContext();
- db.T_UserInfo.Add(model);
- int isOK = db.SaveChanges(); //返回数据是:已写入基础数据库的对象的数目。
- return isOK>0;
- }
- }
- }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace DAL
{
using Models;
public class T_UserInfoDal
{
public List<T_UserInfo> QueryWhere(System.Linq.Expressions.Expression<Func<T_UserInfo, bool>> where)
{
BaseDbContext db = new BaseDbContext();
return db.T_UserInfo.Where(where).ToList();
} public bool AddData(T_UserInfo model)
{
BaseDbContext db = new BaseDbContext();
db.T_UserInfo.Add(model);
int isOK = db.SaveChanges(); //返回数据是:已写入基础数据库的对象的数目。
return isOK>0;
}
}
}
Models
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Models
- {
- using System.ComponentModel.DataAnnotations;
- public class T_UserInfo
- {
- [Key] //因为这里我们并没有直接添加EF,所以意味着这里没有映射实体类的元数据了。所以这里我们要手动的标注主键
- public int id { get; set; }
- public string Name { get; set; }
- public int Age { get; set; }
- }
- }
using System;
using System.Collections.Generic; using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Models
{
using System.ComponentModel.DataAnnotations;
public class T_UserInfo
{
[Key] //因为这里我们并没有直接添加EF,所以意味着这里没有映射实体类的元数据了。所以这里我们要手动的标注主键
public int id { get; set; } public string Name { get; set; } public int Age { get; set; }
}
}
EF| CodeFirst 代码先行的更多相关文章
- .net EF之CodeFirst代码先行(转)
为了支持以设计为中心的开发流程,EF还更多地支持以代码为中心 (code-centric) ,我们称为代码优先的开发,代码优先的开发支持更加优美的开发流程,它允许你在不使用设计器或者定义一个 XML ...
- EF框架搭建小总结--CodeFirst代码优先
前言:之前在下总结编写了一篇 EF框架搭建小总结--ModelFirst模型优先 博文,看到一段时间内该博文的访问量蹭.蹭蹭.蹭蹭蹭...往上涨(实际也不是很多,嘿嘿),但是还是按捺不住内心的喜悦(蛮 ...
- 1.【使用EF Code-First方式和Fluent API来探讨EF中的关系】
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/relationship-in-entity-framework-using-code-firs ...
- Entity Framework 数据库先行、模型先行、代码先行
数据库先行(Database First):基于已存在的数据库,利用某些工具(如Vs提供的EF设计器)创建实体类,数据库对象与实体类的匹配关系等,你也可以手动修改这些自动生成的代码及匹配文件. 模型先 ...
- [.NET领域驱动设计实战系列]专题一:前期准备之EF CodeFirst
一.前言 从去年已经接触领域驱动设计(Domain-Driven Design)了,当时就想自己搭建一个DDD框架,所以当时看了很多DDD方面的书,例如领域驱动模式与实战,领域驱动设计:软件核心复杂性 ...
- EF CodeFirs 代码迁移、数据迁移
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精 标题叫EF CodeFirs 代码迁移.数据迁移. ...
- EF CodeFirst 如何通过配置自动创建数据库<当模型改变时>
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精 本篇为进阶篇,也是弥补自己之前没搞明白的地方,惭愧 ...
- EF CodeFirst增删改查之‘CRUD’
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精 本篇旨在学习EF增删改查四大操作 上一节讲述了EF ...
- EF CodeFirst 创建数据库
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精 话说EF支持三种模式:Code First M ...
随机推荐
- Java基础之流程控制
一.顺序结构 顺序结构的程序语句只能被执行一次.如果您想要同样的操作执行多次,,就需要使用循环结构. if-else-if 语句 语法: if(条件){ 当条件为true时,执行大括号内的代码 }el ...
- mysql千万级大数据SQL查询优化30条经验
转自http://blog.163.com/zhangjie_0303/blog/static/9908270620146951355834/ 1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 w ...
- CSRF原理
全称跨站伪造
- 一个比较难忘的BUG
本学期开设了软件测试课程,在课上有讨论到bug,想到bug,真是很令人头疼的东西,相信每个程序都多多少少会有几个头疼的bug. 初学java时写过一个字符串判断的循环,之前学的C++字符类型用“==” ...
- storm-sql-kafka问题情况
首先上官方文档:http://storm.apache.org/releases/1.2.2/storm-sql.html 解决的问题 1.kafka版本不对 开始测试时采用storm1.2.2+ka ...
- CCF CSP 201812-1 小明上学
题目链接:http://118.190.20.162/view.page?gpid=T80 问题描述 试题编号: 201812-1 试题名称: 小明上学 时间限制: 1.0s 内存限制: 512.0M ...
- React 列表页面传递参数
React 列表进入详情页面 首先安装 react-router-dom (4.0) npm/yarn install react-router-dom 路由跳转配置 列表 父组件 this.prop ...
- 使用aspx 直接生成excel
<%@ Page Language="C#" EnableEventValidation="false" ResponseEncoding="g ...
- gzip对字符串的压缩和解压
package org.jc.plugins.gzip; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStre ...
- 使用nginx代理kibana并配置登录验证
由于kibana不支持登录验证,谁都可以访问,放到公网就不合适了,这里配置用nginx进行代理: 生成密码文件 如果安装了httpd可以用htpasswd,比较方便: htpasswd -c /roo ...