.NET E F(Entity Framework)框架 DataBase First 和 Code First 简单用法。
EF是微软.NET平台官方的ORM(objet-relation mapping),就是一种对象-关系 映射,是将关系数据库种的业务数据用对象的形式表现出来,并通过面向对象的方式讲这些对象组织起来,实现系统业务逻辑的过程。
DataBase First 开发方式
DataBase First 又叫数据库优先的开发方式,是一种比较旧的开发方式,现在越来越多的企业已经不再使用这种开发方式了。当然,对于一些旧项目进行升级,在已经有了数据库的情况下,使用此方式是十分方便的。
使用方法
(1)在项目中右键添加新项,找到ADO.NE实体数据库模型(在c#项下的数据里面)。

下一步

实现增删改查

代码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace mvc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
BooksEntities db = new BooksEntities();
private void Form1_Load(object sender, EventArgs e)
{
//dataGridView1.DataSource = db.Management.ToList();
//默认第一页
label2.Text = "1";
//初始化下拉列表
PageSize();
//获取每页显示数据条数
int pagesize = Convert.ToInt32(comboBox1.SelectedItem);
//获取数据总数
int count = db.Management.Count();
BinData(pagesize, count, x => x.图书编号 > 0);
}
//查询.排序
bool isClick = false;//判断查询按钮是否点击
Management book = new Management();//新建数据实体对象
//定义一个BinData方法连接数据
private void BinData(int pagesize, int count, Expression<Func<Management, bool>> where)
{
dataGridView1.DataSource = null;
//dataGridView1.AutoGenerateColumns = false;//自动创建列 或者关闭自动手动添加
//获取总页数
int pagecount = Convert.ToInt32(Math.Ceiling(count * 1.0 / pagesize));
label3.Text = pagecount.ToString();
//当前页面
int currentpage = Convert.ToInt32(label2.Text);
//查询、排序
dataGridView1.DataSource = GetPagedList<int>(currentpage, pagesize, where, x => x.图书编号);
btnfirst.Enabled = true;
btnpre.Enabled = true;
btnnext.Enabled = true;
btnlast.Enabled = true;
//当前页为第一页时,首页,上一页按钮不能点击,当前页为尾页时,下一页按钮不能点击,当数据
//用一页就可以显示完成,禁用首页,上一页,下一页,尾页按钮
if (currentpage == 1 && count <= pagesize)
{
btnfirst.Enabled = false;
btnpre.Enabled = false;
btnnext.Enabled = false;
btnlast.Enabled = false;
}
else if (currentpage == 1)
{
btnfirst.Enabled = false;
btnpre.Enabled = false;
}
else if (currentpage == pagecount)
{
btnnext.Enabled = false;
btnlast.Enabled = false;
}
}
//初始化每页显示的数据条数
private void PageSize()
{
comboBox1.Items.Clear();
comboBox1.Items.AddRange(new string[] { "5", "10", "50", "100" });
comboBox1.SelectedIndex = 0;
}
//获取分页列表方法
public List<Management> GetPagedList<Tkey>(int currentpag, int pagesize, Expression<Func<Management, bool>> where, Expression<Func<Management, Tkey>> orderBy)
{
return db.Management.Where(where).OrderBy(orderBy).Skip((currentpag - 1) * pagesize).Take(pagesize).ToList();
}
private void isCondition()
{
if (!string.IsNullOrEmpty(textBox1.Text.Trim()) && isClick)
{
BinData(Convert.ToInt32(comboBox1.SelectedItem), db.Management.Where(x => x.书名.Contains(textBox1.Text.Trim())).Count(), x => x.书名.Contains(textBox1.Text.Trim()));
}
else
{
BinData(Convert.ToInt32(comboBox1.SelectedItem), db.Management.Count(), x => x.图书编号 > 0);
}
}
private void button4_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() != null)
{
dataGridView1.DataSource = db.Management.Where(x => x.书名.Contains(textBox1.Text.Trim())).ToList();
}
else
{
Form1_Load(null, null);
}
}
private void button1_Click(object sender, EventArgs e)
{
insert insertfrom = new insert();
insertfrom.Show();
}
private void button3_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(dataGridView1.CurrentRow.Cells["图书编号"].Value);
if (MessageBox.Show("您确定要删除么?", "提示消息", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Management book = db.Management.FirstOrDefault(x => x.图书编号 == id);
if (book != null)
{
db.Management.Remove(book);
db.SaveChanges();
MessageBox.Show("删除成功!");
Form1_Load(null, null);
}
}
}
private void button5_Click(object sender, EventArgs e)
{
for (int i = 0; i < 50; i++)
{
Management book = new Management()
{
书名 = "天龙八部" + i,
作者 = "金庸",
单价 = 1 + i
};
db.Management.Add(book);
}
db.SaveChanges();
Form1_Load(null, null);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label2.Text = "1";
isCondition();
}
private void btnfirst_Click(object sender, EventArgs e)
{
label2.Text = "1";
isCondition();
}
private void btnpre_Click(object sender, EventArgs e)
{
label2.Text = (Convert.ToInt32(label2.Text)-1).ToString();
isCondition();
}
private void btnnext_Click(object sender, EventArgs e)
{
label2.Text = (Convert.ToInt32(label2.Text) + 1).ToString();
isCondition();
}
private void btnlast_Click(object sender, EventArgs e)
{
label2.Text = label3.Text;
isCondition();
}
}
}
以上代码不懂得欢迎评论。(我会经常看的)
以上代码比较难理解的就是可以把lambda表达式做为参数,这是一个比较通用的方法。
CodeFirst
CodeFirst开发方式又叫做代码优先,是用代码创建数据库。EF提供了通过类型的结构推断生成SQL并创建数据库种的表,而且能够通过类型的成员推断出实体间的关系,我们只需要编写实体类就可以进行EF数据库开发:
如果你已经有EF框架
可以右键 引用,添加新项找到
添加引用
没有的话右键管理NuGet程序包
找到EF框架安装。
在项目中添加BookDB类(数据库)和Book类(表) 代码如下:
BookDB
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace codefirst
{
public class BookDB:DbContext//内存上下文可以理解为内存数据库
{
public BookDB()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<BookDB, ConfigurationS>());
}
//默认生成的表名为类型的复数
public DbSet<Book> book { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public class ConfigurationS : DbMigrationsConfiguration<BookDB>
{
public ConfigurationS()
{
// 开启自动迁移
AutomaticMigrationsEnabled = true;
//迁移的时候是否允许数据丢失
AutomaticMigrationDataLossAllowed = true;
}
}
}
}
Book
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace codefirst
{
public class Book
{
public int BookID { get; set; }
public string BookName { get; set; }
public string Author { get; set; }
public decimal Price { get; set; }
}
}
代码优先,需要配置一下App.config文件
<connectionStrings>
<add name="BookDB" connectionString="server=.;uid=sa;pwd=macong123.;database=BookDB" providerName="System.Data.SqlClient"/>
</connectionStrings>
EF约定
表名后面会自动加s(复数形式)
ID列或类名+ID列约定为主键,int类型的主键约定为自增长(从1开始)。
属性名为类名,约定为导航属性(对应数据库中的关系)。
一般的集合或者数组都实现了IEnumberable
EF并不是万能的,有些特殊的SQL语句还是需要直接查询。
用法可以百度 :EF中执行SQL
最后欢迎观看CoolDog的博客园。
.NET E F(Entity Framework)框架 DataBase First 和 Code First 简单用法。的更多相关文章
- 深入了解Entity Framework框架及访问数据的几种方式
一.前言 1.Entity Framework概要 Entity Framework是微软以ADO.NET为基础所发展出来的对象关系映射(O/R Mapping)解决方案.该框架曾经为.NET Fra ...
- 《ASP.NET MVC4 WEB编程》学习笔记------Entity Framework的Database First、Model First和Code Only三种开发模式
作者:张博出处:http://yilin.cnblogs.com Entity Framework支持Database First.Model First和Code Only三种开发模式,各模式的开发 ...
- ASP.NET Core 配置 Entity Framework Core - ASP.NET Core 基础教程 - 简单教程,简单编程
原文:ASP.NET Core 配置 Entity Framework Core - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core 配置 Entity Fram ...
- Entity Framework 之Database first(数据库优先)&Model First(模型优先)
一.什么是Entity Framework 1.1 实体框架(EF)是一个对象关系映射器,使.NET开发人员使用特定于域的对象与关系数据.它消除了需要开发人员通常需要编写的大部分数据访问代码.简化了原 ...
- C# ORM—Entity Framework 之Database first(数据库优先)&Model First(模型优先)(一)
一.什么是Entity Framework 1.1 实体框架(EF)是一个对象关系映射器,使.NET开发人员使用特定于域的对象与关系数据.它消除了需要开发人员通常需要编写的大部分数据访问代码.简化了原 ...
- Entity Framework 框架
微软官方提供的ORM技术的实现就是EF(Entity Framework)框架.EF的模式有三种分别是:Database First 数据库先行 ,Model First 模型先行 , Code F ...
- Entity Framework框架 (一)
1. Entity Framework的详细介绍: Entity Framework简称EF,与Asp.net关系与Ado.net关系. Entity Framework是ado.net中的一组支持开 ...
- Entity Framework 5.0系列之Code First数据库迁移
我们知道无论是"Database First"还是"Model First"当模型发生改变了都可以通过Visual Studio设计视图进行更新,那么对于Cod ...
- Entity Framework 学习系列(3) - MySql Code First 开发方式+数据迁移
目录 # 写在前面 一.开发环境 二.创建项目 三.安装程序包 四.创建模型 五.连接字符串 六.编辑程序 七.数据迁移 写在最后 # 写在前面 这几天,一直都在学习Entity Framework ...
随机推荐
- 初学python-day2 字符串格式化1
- 深入理解Java虚拟机之类加载机制篇
概述 虚拟机把描述类的数据从 Class 文件加载到内存中,并对数据进行校验.转换解析和初始化,最终形成可以被虚拟机直接使用的Java类型,就是虚拟机的类加载机制. 在Java语言里面,类型的 ...
- 6月6日 Scrum Meeting
日期:2021年6月6日 会议主要内容概述: 删除模板选择页面,画图页面新增模板选择 保存时后端判重 后端要新增数据分享url 主题色->lxd:画图教程->lsp:表格数据分析-> ...
- Noip模拟16 2021.7.15
题目真是越来越变态了 T1 Star Way To Heaven 首先,你要看出这是一个最小生成树的题(妙吧?) 为什么可以呢? 我们发现从两点连线的中点过是最优的,但是上下边界怎么办呢? 我们把上下 ...
- 【BZOJ 1419】Red is good [概率DP]
我 是 Z Z 概率好玄啊(好吧是我太弱.jpg Description 桌面上有R张红牌和B张黑牌,随机打乱顺序后放在桌面上,开始一张一张地翻牌,翻到红牌得到1美元,黑牌则付出1美元.可以随时停止翻 ...
- CCD摄像头视场角计算公式
视场角大小和CCD传感器尺寸和镜头焦距有关: 水平视场角 = 2 × arctan(w / 2f); 垂直视场角 = 2 × arctan(h / 2f); 视场角 = 2 × arctan(d / ...
- 【做题记录】DP 杂题
P2577 [ZJOI2004]午餐 $\texttt{solution}$ 想到贪心: 吃饭慢的先打饭节约时间, 所以先将人按吃饭时间从大到小排序. 状态: \(f[i][j]\) 表示前 \(i\ ...
- 创建线程 出现SIGSEGV crash
在Opwrt平台上测试ok的一个网络传输延时测试demo程序移植到Android平台后,运行出现莫名其妙的SIGSEGV crash. 仔细检查过源码,特别是指针等后未发现问题. --------- ...
- Python matplotlib pylot和pylab的区别
matplotlib是Python中强大的绘图库. matplotlib下pyplot和pylab均可以绘图. 具体来说两者的区别 pyplot 方便快速绘制matplotlib通过pyplot模块提 ...
- DeWeb第1个通用化模块:登录模块,仅需要修改一个配置文件即可实现登录功能
演示: https://delphibbs.com/login.dw 开发环境和源代码 https://gitee.com/xamh/dewebsdk 效果图: 配置方法: 在Runtime目录中放一 ...