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

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.Data.Entity;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Configuration;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Remoting.Contexts;
using System.Text;
using DBContext;

namespace DBContext {
    /// <summary>
    /// static data repo,you donot need to reference entity framework
    /// </summary>
    public class SimpleDataRepo {
        public static void Add<T>(T model) where T : IEntityWithKey {
            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 Delete<T>(T model) where T : IEntityWithKey {
            if (model == null) return;
            using (var context = DataContext.Context) {
                context.Attach(model);
                context.DeleteObject(model);
                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;
            }
        }

        /// <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 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();
            }
        }

    }
}

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();
            }
        }
    }
}
时间: 2024-09-29 19:43:22

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

“System.Data.Entity.ModelConfiguration.ModelValidationException”类型的未经处理的异常在 EntityFramework.dll 中发生

下面是错误位置.

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

使用MVC和EF,在保存数据的时候报错:System.Data.Entity.Validation.DbEntityValidationException: 对一个或多个实体的验证失败.有关详细信息,请参阅"EntityValidationErrors"属性. 日志记录中,出错的地方在result += db.SaveChanges();所在行,尝试如下操作: →使用try...catch捕获→在catch所在行打上断点,运行,F11,对ex变量添加监视→在EntityValidati

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

在一开始时将connectionStrings 写在了configSections之上如下图一示,结果抛出:“System.Data.Entity.Internal.AppConfig”的类型初始值设定项引发异常. 图一:最初配置 图二:抛出异常 解决方法,是将connectionStrings 写在了configSections之下,如图三 图三:调整后的配置

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

错误描述: 1 类型“System.Data.Entity.DbContext”在未被引用的程序集中定义.必须添加对程序集“EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”的引用. D:\HF_Source\webapitest\test2\DFSoft.Plat.SQLServerDAL\BaseService\B_AgreementTypeDAL.cs 30 13 DFSof

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

发生System.Data.Entity.Validation.DbEntityValidationException这个异常的时候,如果没有用特定的异常类去捕捉,是看不到具体信息的. 通常都是用System.Data.Entity.Validation.DbEntityValidationException去捕捉: try { // 写数据库 } catch (DbEntityValidationException dbEx ) { } 这个时候再去看就可以看到了.

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

<connectionStrings> <add name="ConnectionStringName" providerName="System.Data.SqlClient" connectionString="Data Source=.;Initial Catalog=DataBaseName;Integrated Security=True;Pooling=False" /> </connectionStri

在mvc返回JSON时出错:序列化类型为“System.Data.Entity.DynamicProxies.Photos....这个会的对象时检测到循环引用 的解决办法

在MVC中返回JSON时出错,序列化类型为“System.Data.Entity.DynamicProxies.Photos....这个会的对象时检测到循环引用. public ActionResult GetSdirsbyFdirid(int id) { // db.Configuration.LazyLoadingEnabled = false; db.Configuration.ProxyCreationEnabled = false; List<Seconddirectory> lis

System.Security.SecurityException The type initializer for &#39;System.Data.Entity.Internal.AppConfig&#39; threw an exception

[15/08/19 00:03:10] [DataManager-7292-ERROR] System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeInitializationException: The type initializer for 'System.Data.Entity.Internal.AppConf

序列化类型为“System.Data.Entity.DynamicProxies...&quot;对象时检测到循环引用

这是因为EF外键引起的序列化问题. 解决方案: context.Configuration.ProxyCreationEnabled = false; 这里我用的是一个基类控制器用于被继承 返回EF实例前加上这段代码就可以了 1 //用于被继承 2 public class BaseController : Controller 3 { 4 public CucuCarEntity db 5 { 6 get 7 { 8 //从当前线程中获取该对象 9 CucuCarEntity db = Cal