EF_简单的增删改查
EF分为三种code_first,model_first,dabase_first这三种模式,网上的例子有好多,但是用了之后感觉实际中都不是这么用的,此处记录写下来日后用的着了可以快速应用,记录如下:
新建项目添加EF6.2
需要四个东西:
1.表对应的model实例,此例中为: shop_test
2.EF连接数据的对象类,此例中为: EF_DATA_DBCONTEXT
3.数据操作的接口类,此例中为: IRepository
4.数据实际操作类,实现接口IRespository的类,此例中为: DataAccessObject

1.shop_test
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace EF_TEST
{
[DataContract]
[Serializable]
[Table("shop_test")]
public partial class shop_test
{
[DataMember(Name ="id")]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
[DataMember(Name ="shopname")]
public string shopname { get; set; }
[DataMember(Name ="create_time")]
public DateTime create_time { get; set; }
[DataMember(Name ="test_msg")]
public string test_msg { get; set; }
}
}
2.EF_DATA_DBCONTEXT
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace EF_TEST
{
//用EF进行连接时需要指定的连接数据库的
class EF_DATA_DBCONTEXT:DbContext
{
public EF_DATA_DBCONTEXT(string contr) : base(contr)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//base.OnModelCreating(modelBuilder);
}
public DbSet<shop_test> shoptests { get; set; }
}
}
3.IRepository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace EF_TEST
{
interface IRepository
{
DbContext CurrentDbContext
{
get;
}
DbEntityEntry<T> Attach<T>(T entity) where T : class;
T Insert<T>(T entity) where T : class;
T Insert<T>(T entity, bool isCommit) where T : class;
void InsertRange<T>(IEnumerable<T> entities) where T : class;
void InsertRange<T>(IEnumerable<T> entities, bool isCommit) where T : class;
void Update<T>(T entity) where T : class;
void Update<T>(T entity, bool isCommit) where T : class;
void UpdateRange<T>(IEnumerable<T> entities) where T : class;
void UpdateRange<T>(IEnumerable<T> entities, bool isCommit) where T : class;
void Delete<T>(T entity) where T : class;
void Delete<T>(T entity, bool isCommit) where T : class;
void DeleteRange<T>(IEnumerable<T> entities) where T : class;
void DeleteRange<T>(IEnumerable<T> entities, bool isCommit) where T : class;
T Find<T>(params object[] keyValues) where T : class;
T Find<T>(object keyValue) where T : class;
List<T> FindAll<T>(Expression<Func<T, bool>> conditions = null) where T : class;
List<T> FindAllByPage<T, S>(Expression<Func<T, bool>> conditions, Expression<Func<T, S>> orderBy, int pageSize, int pageIndex) where T : class;
int SaveChanges();
}
}
4.DataAccessObject
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Linq.Expressions;
using System.Data.Entity.Infrastructure;
using System.Data;
namespace EF_TEST
{
class DataAccessObject:IRepository,IDisposable
{
private DbContext _currentDbContext = null;
public DbContext CurrentDbContext
{
get
{
return this._currentDbContext;
}
}
public DataAccessObject(DbContext dbContext)
{
this._currentDbContext = dbContext;
}
public DbEntityEntry<T> Attach<T>(T entity) where T : class
{
DbSet<T> dbSet = this._currentDbContext.Set<T>();
dbSet.Attach(entity);
return this._currentDbContext.Entry<T>(entity);
}
public T Insert<T>(T entity) where T : class
{
return this.Insert<T>(entity, true);
}
public T Insert<T>(T entity, bool isCommit) where T : class
{
this._currentDbContext.Set<T>().Add(entity);
if (isCommit)
{
this._currentDbContext.SaveChanges();
}
return entity;
}
public void InsertRange<T>(IEnumerable<T> entities) where T : class
{
this.InsertRange<T>(entities, true);
}
public void InsertRange<T>(IEnumerable<T> entities, bool isCommit) where T : class
{
this._currentDbContext.Set<T>().AddRange(entities);
if (isCommit)
{
this._currentDbContext.SaveChanges();
}
}
public void Update<T>(T entity) where T : class
{
this.Update<T>(entity, true);
}
public void Update<T>(T entity, bool isCommit) where T : class
{
this._currentDbContext.Set<T>().Attach(entity);
//this._currentDbContext.Entry<T>(entity).set_State(16);
this._currentDbContext.Entry<T>(entity).State = EntityState.Modified;
if (isCommit)
{
this._currentDbContext.SaveChanges();
}
}
public void UpdateRange<T>(IEnumerable<T> entities) where T : class
{
this.UpdateRange<T>(entities, true);
}
public void UpdateRange<T>(IEnumerable<T> entities, bool isCommit) where T : class
{
foreach (T current in entities)
{
this._currentDbContext.Set<T>().Attach(current);
// this._currentDbContext.Entry<T>(current).set_State(16);
this._currentDbContext.Entry<T>(current).State = EntityState.Modified;
}
if (isCommit)
{
this._currentDbContext.SaveChanges();
}
}
public void Delete<T>(T entity) where T : class
{
this.Delete<T>(entity, true);
}
public void Delete<T>(T entity, bool isCommit) where T : class
{
this._currentDbContext.Set<T>().Remove(entity);
if (isCommit)
{
this._currentDbContext.SaveChanges();
}
}
public void DeleteRange<T>(IEnumerable<T> entities) where T : class
{
this.DeleteRange<T>(entities, true);
}
public void DeleteRange<T>(IEnumerable<T> entities, bool isCommit) where T : class
{
this._currentDbContext.Set<T>().RemoveRange(entities);
if (isCommit)
{
this._currentDbContext.SaveChanges();
}
}
public int SaveChanges()
{
return this._currentDbContext.SaveChanges();
}
public T Find<T>(params object[] keyValues) where T : class
{
return this._currentDbContext.Set<T>().Find(keyValues);
}
public T Find<T>(object keyValue) where T : class
{
object[] array = new object[]
{
keyValue
};
return this._currentDbContext.Set<T>().Find(array);
}
public List<T> FindAll<T>(Expression<Func<T, bool>> conditions = null) where T : class
{
List<T> result;
if (conditions == null)
{
result = this._currentDbContext.Set<T>().ToList<T>();
}
else
{
result = this._currentDbContext.Set<T>().Where(conditions).ToList<T>();
}
return result;
}
public List<T> FindAllByPage<T, S>(Expression<Func<T, bool>> conditions, Expression<Func<T, S>> orderBy, int pageSize, int pageIndex) where T : class
{
IQueryable<T> source = (conditions == null) ? this._currentDbContext.Set<T>() : this._currentDbContext.Set<T>().Where(conditions);
return source.OrderByDescending(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList<T>();
}
public void Dispose()
{
this._currentDbContext.Dispose();
}
}
}
控制台程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Transactions;
namespace EF_TEST
{
class Program
{
static void Main(string[] args)
{
//config中的数据库的连接字符串
string CONSTR = System.Configuration.ConfigurationManager.ConnectionStrings["CONSTR"].ConnectionString;
//EF的DB连接对象
EF_DATA_DBCONTEXT db = new EF_DATA_DBCONTEXT(CONSTR);
//实现的的具体方法
IRepository DB_LINK = new DataAccessObject(db);
//进行的查询操作
List<shop_test> msg = DB_LINK.FindAll<shop_test>(p => p.id >= 0);
Console.WriteLine("查询ID大于0的所有数据");
Console.WriteLine("共查询到的信息行数:{0}--最后一个数据的时间:{1}", msg.Count, msg.Max(u => u.create_time).ToString());
//插入操作
shop_test insert_shop = new shop_test() { shopname="test", test_msg="ss", create_time =DateTime.Now };
using (TransactionScope scope =new TransactionScope() )
{
DB_LINK.Insert<shop_test>(insert_shop,false);
shop_test insert_second = new shop_test() { shopname=insert_shop.shopname, test_msg=insert_shop.test_msg, create_time=DateTime.Now };
DB_LINK.Insert<shop_test>(insert_second, false);
DB_LINK.SaveChanges();
scope.Complete();
}
Console.WriteLine("插入的id:{0}--shopname {1}---test_msg:{2} ---create_time:{2}", insert_shop.id, insert_shop.shopname, insert_shop.test_msg, insert_shop.create_time);
//更新操作
msg = DB_LINK.FindAll<shop_test>(u => u.id > 0);
Console.WriteLine("查询ID大于0的所有数据");
Console.WriteLine("共查询到的信息行数:{0}--最后一个数据的时间:{1}", msg.Count, msg.Max(u => u.create_time));
//更新操作,更新最大时间为当前时间
shop_test update_shop = (from i in msg
let max_time = msg.Max(u => u.create_time)
where i.create_time == max_time
select i
).FirstOrDefault();
update_shop.create_time = DateTime.Now;
DB_LINK.Update<shop_test>(update_shop);
Console.WriteLine("更新的id:{0}--shopname {1}---test_msg:{2} ---create_time:{2}", insert_shop.id, insert_shop.shopname, insert_shop.test_msg, insert_shop.create_time);
//删除操作;
Console.WriteLine("查询ID大于0的所有数据");
Console.WriteLine("共查询到的信息行数:{0}--最后一个数据的时间:{1}", msg.Count, msg.Max(u => u.create_time));
//删除操作 删除时间最早的数据
msg = DB_LINK.FindAll<shop_test>(u => u.id > 0);
shop_test delete_shop = (from i in msg
let max_time = msg.Max(u => u.create_time)
where i.create_time == max_time
select i
).FirstOrDefault();
DB_LINK.Delete<shop_test>(delete_shop);
Console.WriteLine("删除的id:{0}--shopname {1}---test_msg:{2} ---create_time:{2}", insert_shop.id, insert_shop.shopname, insert_shop.test_msg, insert_shop.create_time);
Console.WriteLine("查询ID大于0的所有数据");
Console.WriteLine("共查询到的信息行数:{0}--最后一个数据的时间:{1}", msg.Count, msg.Max(u=>u.create_time));
Console.ReadKey();
}
}
}
配置文件,及其数据库的表结构:
<connectionStrings>
<!--<add name="CONSTR" connectionString="DATA SOURCE=127.0.0.1;INITIAL CATALOG=TEST;USER ID=SA;PASSWORD=123"/>-->
<add name="CONSTR" connectionString="Data Source=127.0.0.1;Database=TEST;UID=sa;PWD=123;" providerName="System.Data.SqlClient"/>
</connectionStrings>
CREATE TABLE [dbo].[shop_test](
[id] [INT] IDENTITY(1,1) NOT NULL,
[shopname] [VARCHAR](50) NULL,
[create_time] [DATETIME] NULL,
CONSTRAINT [PK_shop_test] PRIMARY KEY NONCLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
)
EF_简单的增删改查的更多相关文章
- salesforce 零基础学习(五十一)使用 Salesforce.com SOAP API 实现用户登录以及简单的增删改查(JAVA访问salesforce)
此篇请参看:https://resources.docs.salesforce.com/202/latest/en-us/sfdc/pdf/salesforce_developer_environme ...
- MyBatis学习--简单的增删改查
jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: Public static void main(String[] args) ...
- 通过JDBC进行简单的增删改查
通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操 ...
- MyBatis简单的增删改查以及简单的分页查询实现
MyBatis简单的增删改查以及简单的分页查询实现 <? xml version="1.0" encoding="UTF-8"? > <!DO ...
- 初试KONCKOUT+WEBAPI简单实现增删改查
初试KONCKOUT+WEBAPI简单实现增删改查 前言 konckout.js本人也是刚刚接触,也是初学,本文的目的是使用ko和asp.net mvc4 webapi来实现一个简单增删改查操作.Kn ...
- MVC3.0+knockout.js+Ajax 实现简单的增删改查
MVC3.0+knockout.js+Ajax 实现简单的增删改查 自从到北京入职以来就再也没有接触MVC,很多都已经淡忘了,最近一直在看knockout.js 和webAPI,本来打算采用MVC+k ...
- SpringMVC之简单的增删改查示例(SSM整合)
本篇文章主要介绍了SpringMVC之简单的增删改查示例(SSM整合),这个例子是基于SpringMVC+Spring+Mybatis实现的.有兴趣的可以了解一下. 虽然已经在做关于SpringMVC ...
- python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作
1.通过 pip 安装 pymysql 进入 cmd 输入 pip install pymysql 回车等待安装完成: 安装完成后出现如图相关信息,表示安装成功. 2.测试连接 import ...
- 通过flask实现web页面简单的增删改查bootstrap美化版
通过flask实现web页面简单的增删改查bootstrap美化版 项目目录结构 [root@node1 python]# tree -L 2 . ├── animate.css ├── fileut ...
随机推荐
- VirtualBox虚拟机禁止时间同步
某机器为客户提供,宿主机时间快了20分钟,导致虚拟机时间也跟着快20分钟,每次更改完虚拟机时间,不到1分钟时间又变回去了 在一些情况下必须让VirtualBox虚拟客户机的时间和主机不同步,百度了一番 ...
- 用 EPWA 写一个 图片播放器 PicturePlayer
用 EPWA 写一个 图片播放器 PicturePlayer . 有关 EPWA,见 <我发起并创立了一个 EPWA 的 开源项目> https://www.cnblogs.com ...
- 浏览器输入url回车后,会发生什么?
通常我们想访问某一个网址,我们会在浏览器中输入它的域名,然后点击回车进行跳转,这样就可以进到网站的主页,看似简单的两步,其实背后都需要大量的代码在运行,支持,才能完成!那浏览器到底都做了哪些事呢? 一 ...
- 第一章 XAML概览
1.1 XAML是什么? XAML是eXtensible Application Markup Language的英文缩写,相应的中文名称为可扩展应用程序标记语言.也就是说在开发一个应用程序时,我们可 ...
- log4j-over-slf4j和slf4j-log4j12冲突问题解决
解决办法: 两个jar包会循环引用导致内存溢出.解决的办法就是将两个jar包其中一个的依赖移除掉
- Java面向对象程序设计的六大基本原则
1.开闭原则(Open Close Principle) 定义:一个软件实体如类.模块和函数应该对扩展开放,对修改关闭. 开放-封闭原则的意思就是说,你设计的时候,时刻要考虑,尽量让这个类是足够好,写 ...
- 华为4K机顶盒EC6108V9U从原联通更换为电信的IPTV账号成功经验
4K设备直接在淘宝上买30块钱升级4K机顶盒,i视视手机app控制电视和手机投屏 硬件设备:EC6108V9U由X省联通更换为四川电信 采坑经验: 1.要从现有的机顶盒获取mac地址.stbid.ip ...
- centos7 php-apache镜像添加redis/memcache/gd/mysql_pdo/mysqli/imagick
FROM php:5.6-apache-stretch RUN /usr/local/bin/docker-php-ext-install mysqli pdo_mysql; \ && ...
- mysql导入sql文件出错的一种解决方法
转:https://blog.csdn.net/u011806486/article/details/60147358 本人在本地使用navicat for mysql可以连接到服务器数据库,但是从服 ...
- 在命令行终端运行 Elisp 脚本
通常,我们在 Emacs 中运行 Elisp 代码片段,但是也可能需要在命令行终端运行 Elisp 脚本程序.在命令行终端运行 Elisp 脚本需要使用 --script 选项,例如: emacs - ...