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. PHP Socket服务器搭建和测试

    1.socket服务器搭建思路 1) 目的:理解socket服务器工作机制 2) 思路:创建socket -> 把socket加入连接池 -> 处理接收信息 -> 握手动作 -> ...

  2. Linux下 VI 编辑器操作

    VI编辑器的三种模式:命令模式.输入模式.末行模式. 1.命令模式:vi启动后默认进入的是命令模式,从这个模式使用命令可以切换到另外两种模式,同时无论在何种模式下,[Esc]键都可以回到命令模式.在命 ...

  3. 通过集群的方式解决基于MQTT协议的RabbitMQ消息收发

    在完成了基于AMQP协议的RabbitMQ消息收发后,我们要继续实现基于MQTT协议的RabbitMQ消息收发. 由于C#的RabbitMQ.Client包中只实现了基于AMQP协议的消息收发功能的封 ...

  4. 13 Django组件-cookie与session

    会话跟踪技术 1 什么是会话跟踪技术 我们需要先了解一下什么是会话!可以把会话理解为客户端与服务器之间的一次会晤,在一次会晤中可能会包含多次请求和响应.例如你给10086打个电话,你就是客户端,而10 ...

  5. 5 Post实现django表单

    本节大纲 1.article-detail 评论页面的准备工作 (1)model层创建评论模型 class Comment(models.Model): """创建评论模 ...

  6. android:windowBackground 和 Android:background 的区别

    通过问别人,我知道了android:windowBackground 和 Android:background的区别 android:windowBackground 一般用于activity启动的时 ...

  7. 腾讯课堂之前端开发html5css3javascriptjQueryJS年薪20万

    第一章 网页制作零基础 第一节 什么是HTML 第二节 HTML基本语法 第三节 HTML结构标签 第四节 HTML常用标签及属性 第五节 HTML无序列表UL标签 第六节 HTML定义列表DL标签 ...

  8. erlang连接mysql [转]

    转自: http://blog.csdn.net/flyinmind/article/details/7740540 项目中用到erlang,同时也用到mysql.惯例,google. 但是,按照网上 ...

  9. viewDidLoad dispatch_sync

    - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"1"); dispatch_sync(dispatch_get_main_qu ...

  10. virsh command

    http://www.cnblogs.com/chenjiahe/category/845519.html resize qemu-img resize win2k8r2.qcow2 40G conv ...