.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 ...
随机推荐
- Linux中使用dd制作文件的.img
dd if=/dev/zero of=new_img.img bs=1M count=20 //生成20M的文件,bs块的大小,count块的数量 mkfs.ext3 new_img.img / ...
- csh
在*unix系统中,常用的shell有sh,bash,csh/tcsh, ksh. sh来自于systemV的Unix,是传统的Unix的shell,直到现在很多的系统管理员仍然喜欢使用sh. ba ...
- Golang通脉之结构体
Go语言中的基础数据类型可以表示一些事物的基本属性,但是要表达一个事物的全部或部分属性时,这时候再用单一的基本数据类型明显就无法满足需求了,Go语言提供了一种自定义数据类型,可以封装多个基本数据类型, ...
- 实现服务器和客户端数据交互,Java Socket有妙招
摘要:在Java SDK中,对于Socket原生提供了支持,它分为ServerSocket和Socket. 本文分享自华为云社区<Java Socket 如何实现服务器和客户端数据交互>, ...
- Mybatis 动态Sql练习
建表 CREATE TABLE `student` ( `s_id` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT ...
- Sequence Model-week1编程题3-用LSTM网络生成爵士乐
Improvise a Jazz Solo with an LSTM Network 实现使用LSTM生成音乐的模型,你可以在结束时听你自己的音乐,接下来你将会学习到: 使用LSTM生成音乐 使用深度 ...
- Scrum Meeting 13
第13次例会报告 日期:2021年06月05日 会议主要内容概述: 团队成员均明确了下一步的目标,进度突飞猛进辣 一.进度情况 我们采用日报的形式记录每个人的具体进度,链接Home · Wiki,如下 ...
- 到底能不能用 join
互联网上一直流传着各大公司的 MySQL 军规,其中关于 join 的描述,有些公司不推荐使用 join,而有些公司则规定有条件的使用 join, 它们都是教条式的规定,也没有详细说其中的原因,这就很 ...
- linux exit 和 _exit的区别
今天仔细看了一下exit和_exit这两个函数的区别,实际上exit也是调用了_exit退出函数的,只不过在调用_exit之前,exit还进行了一些多余的工作,也正是因为这样,相比起来exit就没有那 ...
- MySql数据库索引-聚集索引和辅助索引
InnoDB存储引擎索引: B+树索引:不能找到一个给定键值的具体行,能找到的只是被查找数据行所在的页.然后把页加载到内存,在查询所要的数据. 全文索引: 哈希索引:InnoDB会根据表的使用情况自动 ...