note:you can delete reference of entityframework when using this classes.it`s just a simple repohelper.the code below can also include a getpagedlist method when paging.
have fun,it`s simple,just create edmx file from database.all one sentence.but when using iqueryable or transaction,you need to use context factory and develop your own methods.
i am using it now.very simple.just like a static modelhelper orm.
1.simpledaterepo:
/*
* author:iGo
* for-free
* last-update:2015年7月7日
* auth:mit
* hope it will be useful to you
* */
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions; namespace DBContext {
/// <summary>
/// static data repo,you donot need to reference entity framework
/// </summary>
public class SimpleDataRepo {
public static void Add<T>(T model) {
if (model == null) return;
using (var context = DataContext.Context) {
context.AddObject(typeof(T).Name, model);
context.SaveChanges();
}
} public static void Edit<T>(T model) where T : class {
if (model == null) return;
using (var context = DataContext.Context) {
context.AddObject(model.GetType().Name, model);
context.ObjectStateManager.ChangeObjectState(model, EntityState.Modified);
context.SaveChanges();
}
}
public static void EditCommand<T>(String setCondition, String whereClause) {
if (String.IsNullOrEmpty(setCondition)) return;
using (var context = DataContext.Context) {
context.ExecuteStoreCommand(String.Format("update {0} set {1} where {2}", typeof(T).Name, setCondition, whereClause));
}
} public static void Delete<T>(T model) where T : class {
if (model == null) return;
using (var context = DataContext.Context) {
context.AddObject(model.GetType().Name, model);
context.ObjectStateManager.ChangeObjectState(model, EntityState.Deleted);
context.SaveChanges();
} } [NotUsed("not used due to linq function unsupported!")]
private static int GetPropertyIdValueFromModel<T>(T model) {
return (int)model.GetType().GetProperty("id").GetValue(model, null);
} public static IList<T> GetAll<T>(Expression<Func<T, bool>> condition = null) {
using (var context = DataContext.Context) {
var query = context.GetType().GetProperty(typeof(T).Name).GetValue(context, null) as IQueryable<T>;
return query != null ? query.ToList() : null;
}
} public static IList<T> GetAllCommand<T>(String whereClause = "") {
using (var context = DataContext.Context) {
return context.ExecuteStoreQuery<T>(String.Format("select * from {0} {1}", typeof(T).Name,
String.IsNullOrEmpty(whereClause) ? "" : (" where " + whereClause))).ToList();
}
} /// <summary>
/// Get first model that satisfies the specified condition,GetById can be implied here,ie:a=>a.Id=5
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="condition"></param>
/// <returns></returns>
public static T QueryFirst<T>(Expression<Func<T, bool>> condition) {
using (var context = DataContext.Context) {
var query = context.GetType().GetProperty(typeof(T).Name).GetValue(context, null) as IQueryable<T>;
if (query == null) return default(T);
return query.FirstOrDefault(condition);
}
} public static T QueryFirstCommand<T>(String condition = "") {
using (var context = DataContext.Context) {
return
context.ExecuteStoreQuery<T>(String.Format("select top 1 * from {0} {1}", typeof(T).Name,
String.IsNullOrEmpty(condition) ? "" : (" where " + condition))).FirstOrDefault();
}
} public static IList<T> QuerySort<T, TS>(Expression<Func<T, bool>> condition, Expression<Func<T, TS>> sortExpression = null, bool isDecending = false) {
using (var context = DataContext.Context) {
var query = context.GetType().GetProperty(typeof(T).Name).GetValue(context, null) as IQueryable<T>;
if (query == null) return null;
query = query.Where(condition).Where(condition);
if (sortExpression != null)
query = isDecending ? query.OrderByDescending(sortExpression) : query.OrderBy(sortExpression);
return query.ToList();
}
} public static void DeleteByIds<T>(String ids) {
if (String.IsNullOrEmpty(ids)) throw new ArgumentException("ids cannot be null or empty!");
using (var context = DataContext.Context) {
context.ExecuteStoreCommand(String.Format("delete from {0} where id in ({1})", typeof(T).Name, ids));
context.SaveChanges();
}
} #region web paging field //protected virtual IPagedList<T> GetTPagedList<T, TS>(Expression<Func<T, bool>> filter = null, Expression<Func<T, TS>> orderby = null, bool isDecending = false) where T : new() {
// IPagedList<T> list;
// using (var context = DataContext.Context) {
// var pageIndex = Request["pageNum"] ?? "1";
// var pageSize = Request["numPerPage"] ?? "15"; // Expression<Func<T, bool>> condition = a => true;
// if (filter != null) condition = condition.And(filter);
// var b = context.GetType().GetProperty(typeof(T).Name).GetValue(context, null) as IQueryable<T>;
// if (b == null) return null;
// b = b.Where(condition);
// if (orderby != null)
// b = !isDecending ? b.OrderBy(orderby) : b.OrderByDescending(orderby);
// list = b.ToPagedList(int.Parse(pageIndex), int.Parse(pageSize));
// //b.Skip(int.Parse(pageSize)*(int.Parse(pageIndex) - 1)).Take(int.Parse(pageSize)).ToList();
// }
// return list;
//}
#endregion }
}
 
 2.context factory:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text; namespace DBContext {
public partial class DataContext {
public static GpsDataContext Context {
get {
return new GpsDataContext();
}
}
}
}

写一个system.data.entity的simpledatarepo,实现crudq这些功能,不需要引入entityframework,直接可以使用,用到objectset的更多相关文章

  1. Method not found: 'System.Data.Entity.ModelConfiguration.Configuration.XXX

    使用EF flument API  修改映射数据库字段的自增长 modelBuilder.Entity<Invoice>().Property(p => p.Id).HasDatab ...

  2. 报错:System.Data.Entity.Validation.DbEntityValidationException: 对一个或多个实体的验证失败

    使用MVC和EF,在保存数据的时候报错:System.Data.Entity.Validation.DbEntityValidationException: 对一个或多个实体的验证失败.有关详细信息, ...

  3. 传入字典的模型项的类型为“System.Data.Entity.DynamicProxies.

    今天做东西遇到了,这样的一个问题,最后了半天才找到问题所在,现在给大家分享一下问题所在: 传入字典的模型项的类型为“System.Data.Entity.DynamicProxies.doctorUs ...

  4. System.Security.SecurityException The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

    [15/08/19 00:03:10] [DataManager-7292-ERROR] System.Reflection.TargetInvocationException: Exception ...

  5. EF生成 类型“System.Data.Entity.DbContext”在未被引用的程序集中定义

    错误描述: 1 类型“System.Data.Entity.DbContext”在未被引用的程序集中定义.必须添加对程序集“EntityFramework, Version=5.0.0.0, Cult ...

  6. “System.Data.Entity.Internal.AppConfig"的类型初始值设定项引发异常。{转}

    <connectionStrings> <add name="ConnectionStringName" providerName="System.Da ...

  7. System.Data.Entity.Internal.AppConfig 类型初始值设定项引发异常

    在一开始时将connectionStrings 写在了configSections之上如下图一示,结果抛出:“System.Data.Entity.Internal.AppConfig”的类型初始值设 ...

  8. MVC中发生System.Data.Entity.Validation.DbEntityValidationException验证异常的解决方法

    发生System.Data.Entity.Validation.DbEntityValidationException这个异常的时候,如果没有用特定的异常类去捕捉,是看不到具体信息的. 通常都是用Sy ...

  9. System.Data.Entity.Infrastructure.DbUpdateException

    异常描述:   捕捉到 System.Data.Entity.Infrastructure.DbUpdateException  HResult=-2146233087  Message=无法更新 E ...

随机推荐

  1. MOS管学习笔记

    最近在做一个小的电路设计项目,其中遇到了MOS管,经过查询资料,多年遗忘的数电.模电渐渐又浮现在我的脑海,在百度文库找到一篇比较不错的文章,把它截图使用出来,如原稿作者看到感觉侵权,请及时联系我,以便 ...

  2. McNay Art Museum【McNay艺术博物馆】

    McNay Art Museum When I was 17, I read a magazine artice about a museum called the McNay, once the h ...

  3. [CodeChef]RIN(最小割)

    Description  有m门课可以在n个学期内学习,第i门课在第j个学期的收益是\(X_{i,j}\),一个学期可以学多门课,有的课之间有依赖关系,即必须先学a再学b,求最大收益.n,m<= ...

  4. 为什么不要使用 Async Void ?

    原文:为什么不要使用 Async Void ? 问题 在使用 Abp 框架的后台作业时,当后台作业抛出异常,会导致整个程序崩溃.在 Abp 框架的底层执行后台作业的时候,有 try/catch 语句块 ...

  5. 关于DIV内文字垂直居中的写法

    最近在写UI,或多或少用到了CSS,在这记录一下,今天用到的DIV内文字垂直居中的写法, 因为所做的项目都是基于WebKit内核浏览器演示的,所以我们今天采用的是-webkit-box的写法: dis ...

  6. com.squareup.okhttp.Interceptor

    retrift 集成了okhttp,所以,我们以后就不用再单独的引用http的jar 了. 但是,今天遇到一个问题,就是okhttp是这样设置一些intercept的: private static ...

  7. 【Java集合源码剖析】Java集合框架

    Java集合工具包位于Java.util包下,包含了很多常用的数据结构,如数组.链表.栈.队列.集合.哈希表等.学习Java集合框架下大致可以分为如下五个部分:List列表.Set集合.Map映射.迭 ...

  8. php静态文件返回304

    有时一些静态文件(如图片)会由php输出,会发现请求都是200,静态文件每次都去服务器上请求太浪费资源了,这时如何让浏览器缓存图片呢?就需要我们在php中输出304了. 我们可以利用php中的 HTT ...

  9. Canvas 图形组合方式

    /** * 图形组合 */ function initDemo5() { var canvas = document.getElementById("demo5"); if (!c ...

  10. 使用cloudbase-init初始化windows虚拟机

    CloudBase-init简介 cloudbase-init 是 Windows 和其他系统的云初始化程序,可以设置主机名.创建用户.设置静态ip.设置密码等.对应的linux初始化程序是cloud ...