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. 3 破解密码,xshell连接

    1.破解root密码 (1)启动电脑,按上下键进入启动菜单界面,选择第二个Red Hat Enterprise Linux Server, with Linux 0-rescue-* (2)按 'e' ...

  2. 4.bootstrap的form表单的form-group和form-control的区别与联系

    1. form-group一般用于div form-control一般用于置于div中的标签元素,为了让控件在各种表单风格中样式不出错,需要添加类名“form-control”,如: <form ...

  3. Docker应用设计四大关键

    TechTarget中国原创] Docker已经垄断了容器技术.设计应用时注意考虑便携性能够帮助企业利用容器技术能提供的所有优势. 随着Docker应用和容器越来越流行,很多公司都开始将容器技术作为其 ...

  4. C# 委托、Lambda表达式和事件——学习总结

    1.概括 1.1.委托是寻址方法的.NET版本,类似C++中的指针.委托可以理解成指向函数的指针,它是类型安全的,定义了具体的参数和返回值. ——定义一个委托,实际上是定义一个类.委托是对方法的引用, ...

  5. USACO Section1.4 Mother's Milk 解题报告

    milk3解题报告 —— icedream61 博客园(转载请注明出处)---------------------------------------------------------------- ...

  6. leetcode 【 Linked List Cycle 】 python 实现

    题目: Given a linked list, determine if it has a cycle in it. Follow up:Can you solve it without using ...

  7. Yapi的坑

    前一段时间,研究WEB Api相关的工具. YApi 可以内网部署,内心十分的欢喜啊.而且gitHub上推荐超过4000星,成绩很优异嘛.然而通过最终的尝试,我还是打算放弃他,投入Postman的怀抱 ...

  8. bitbucket相关操作

    常见命令: git checkout -b develop master 创建Develop分支的命令 git checkout master 切换到Master分支 git merge --no-f ...

  9. 原始套接字--traceroute

    traceroute, 也就是 trace route,跟踪路由.这个程序最早是Van Jacobson实现的.源码在网上可以找到,不过我还没有去找.是IP路由过程中对数据包TTL(Time to L ...

  10. c++ devived object model

    单一虚函数继承 class A{public: virtual int foo( ) { return val ; } virtual int funA( ) {}private: int val ; ...