EF_Helper

来源:互联网 发布:超级优化主角几个老婆 编辑:程序博客网 时间:2024/05/20 13:08
 /// <summary>
    /// EF——对象操作-辅助类
    /// </summary>
    /// <typeparam name="M"></typeparam>
    public class EF_Helper<M> where M : DbContext, new()
    {
        /// <summary>
        /// DBEntities
        /// </summary>
        private M sd;
        /// <summary>
        /// 实例化DBEntities
        /// </summary>
        /// <returns></returns>
        private M GetDBEntities()
        {
            if (sd == null)
            {
                sd = new M();
            }
            return sd;
        }
        /// <summary>
        /// 添加数据到对象
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="t">对象名</param>
        /// <returns>true/false</returns>
        public bool Add<T>(T t) where T : class
        {
            M sde = GetDBEntities();
            sde.Set<T>().Add(t);
            return sde.SaveChanges() > 0;
        }
        /// <summary>
        /// 根据条件查询对象并返回对象集合
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="p">条件</param>
        /// <returns>对象集合list</returns>
        public List<T> GetList<T>(Expression<Func<T, bool>> p) where T : class
        {
            M sde = GetDBEntities();
            return sde.Set<T>().Where(p).ToList();
        }
        /// <summary>
        /// 根据条件查询对象
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="p">条件</param>
        /// <returns>对象</returns>
        public T GetNow<T>(Expression<Func<T, bool>> p) where T : class
        {
            M sde = GetDBEntities();
            return sde.Set<T>().Where(p).FirstOrDefault();
        }
        /// <summary>
        /// 修改对象
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="t">对象名称</param>
        /// <returns>true/false</returns>
        public bool Update<T>(T t) where T : class
        {
            M sde = GetDBEntities();
            var ent = sde.Entry<T>(t);
            ent.State = System.Data.EntityState.Unchanged;
            PropertyInfo[] pi = t.GetType().GetProperties();
            for (int i = 0; i < pi.Length; i++)
            {
                object obj = pi[i].GetValue(t);
                if (obj != null)
                {
                    ent.Property(pi[i].Name).IsModified = true;
                }
            }
            return sde.SaveChanges() > 0;
        }
        /// <summary>
        /// 删除对象
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="t">对象名</param>
        /// <returns>true/false</returns>
        public bool Delete<T>(T t) where T : class
        {
            M sde = GetDBEntities();
            var ent = sde.Entry<T>(t);
            ent.State = System.Data.EntityState.Deleted;
            return sde.SaveChanges() > 0;
        }
原创粉丝点击