zoukankan      html  css  js  c++  java
  • 使用EF 的简单的增删改查

    using DAL;
    using Model;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace BLL
    {
        public class InfoManage
        {
            private BaseDal db;
            public InfoManage(BaseDal dal)
            {
                this.db = dal;
            }
    
            public InfoManage()
            {
                this.db = new BaseDal();
            }
            public bool Add(Info lst)
            {
                db.BeginTranscation();
                db.SaveOrUpdate(lst, true);
                return db.Commit() > 0;
            }
    
            public List<Info> GetList()
            {
                return db.GetEntity<Info>().ToList();
            }
        }
    }
    View Code

    ADO.NET Entity Framework 是微软以 ADO.NET 为基础所发展出来的对象关系对应 (O/R Mapping) 解决方案,早期被称为 ObjectSpace。

     1.搭建EF环境

      

       在DAL层添加项目ADO.NET 实体数据库模型

     在Model层添加EF 5.x DbContext生成器

      

    修改inputFile的值

    DAL 代码

      

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace DAL
    {
        public class BaseDal : IDisposable
        {
            private TestEntities db = new TestEntities();
    
            private bool isTransaction = false;
    
            public IQueryable<T> GetEntity<T>() where T : class
            {
                return db.Set<T>().AsNoTracking().AsQueryable<T>();
            }
    
            /// <summary>
            /// 添加
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="lst"></param>
            /// <returns></returns>
            public int Add<T>(List<T> lst, bool isCommit = true) where T : class
            {
                foreach (var item in lst)
                {
                    db.Entry<T>(item).State = System.Data.EntityState.Added;
                }
    
                if (isCommit && !isTransaction)
                    return db.SaveChanges();
                else
                    return 0;
    
            }
    
            /// <summary>
            /// 根据条件删除
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="predicate"></param>
            /// <returns></returns>
            public bool DeleteByCondition<T>(Expression<Func<T, bool>> predicate, bool isCommit = true) where T : class
            {
                db.Set<T>().Where<T>(predicate).ToList<T>().ForEach(d => db.Entry<T>(d).State = System.Data.EntityState.Deleted);
                if (isCommit && !isTransaction)
                    return db.SaveChanges() > 0;
                else
                    return false;
            }
    
            public bool UpdateByCondition<T>(Action<T> updateExpression, Expression<Func<T, bool>> predicate, bool isCommit = true) where T : class
            {
                var lst = db.Set<T>().Where<T>(predicate).ToList<T>();
                lst.ForEach(item =>
                {
                    updateExpression(item);
                    db.Entry<T>(item).State = System.Data.EntityState.Modified;
                });
    
                if (isCommit && !isTransaction)
                    return db.SaveChanges() > 0;
                else
                    return false;
            }
    
            public bool SaveOrUpdate<T>(T entity, bool isAdd = false, bool isCommit = true) where T : class
            {
                if (isAdd)
                    db.Set<T>().Add(entity);
                else
                    db.Entry(entity).State = System.Data.EntityState.Modified;
    
                if (isCommit && !isTransaction)
                    return db.SaveChanges() > 0;
                else
                    return false;
    
            }
    
            public bool SaveOrUpdateForList<T>(List<T> entities, bool isAdd = false, bool isCommit = true) where T : class
            {
                foreach (T entity in entities)
                {
                    if (isAdd)
                        db.Set<T>().Add(entity);
                    else
                        db.Entry(entity).State = System.Data.EntityState.Modified;
                }
                if (isCommit && !isTransaction)
                    return db.SaveChanges() > 0;
                else
                    return false;
            }
    
            public int ExecuteSqlCommand(string sql, bool isCommit = true)
            {
                db.Database.ExecuteSqlCommand(sql);
                if (isCommit && !isTransaction)
                    return db.SaveChanges();
                else
                    return 0;
            }
    
            public int ExecuteSqlCommand(string sql, bool isCommit, params object[] parameters)
            {
                db.Database.ExecuteSqlCommand(sql, parameters);
                if (isCommit && !isTransaction)
                    return db.SaveChanges();
                return 0;
            }
            /// <summary>
            /// 执行存储过程
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="ProcName"></param>
            /// <param name="paramsStr"></param>
            /// <returns></returns>
            public List<T> ExecPro<T>(string ProcName, object[] paramsStr)
            {
                try
                {
                    string sql = "exec " + ProcName;
    
                    if (paramsStr.Length > 0)
                    {
                        string str = string.Empty;
                        for (int i = 0; i < paramsStr.Length; i++)
                        {
                            if (str != string.Empty)
                                str += ",";
    
                            str += "@p" + i.ToString();
                        }
                        sql += " " + str;
                    }
    
                    return db.Database.SqlQuery<T>(sql, paramsStr).ToList();
                }
                catch (Exception ex)
                {
                    return new List<T>();
                }
            }
    
            /// <summary>
            ///  执行存储过程 无超时
            /// </summary>
            /// <param name="ProcName"></param>
            /// <param name="parList"></param>
            public void ExecPro(string ProcName, List<SqlParameter> parList)
            {
                DbConnection conn = db.Database.Connection;
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                DbCommand cmd = conn.CreateCommand();
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = ProcName;
                cmd.CommandTimeout = 0;
                foreach (SqlParameter par in parList)
                {
                    cmd.Parameters.Add(par);
                }
    
                cmd.ExecuteNonQuery();
            }
    
            public void BeginTranscation()
            {
                isTransaction = true;
            }
    
            public int Commit()
            {
                if (isTransaction)
                {
                    isTransaction = false;
                    return db.SaveChanges();
                }
                else
                    return 0;
            }
    
            /// <summary>
            /// 执行SQL查询语句
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <returns></returns>
            public List<T> FindEntityListBySql<T>(string sql)
            {
                return db.Database.SqlQuery<T>(sql).ToList<T>();
            }
    
            public void Close()
            {
                if (db != null)
                {
                    db.Dispose();
                    db = null;
                }
            }
    
            public void Dispose()
            {
                if (db != null)
                {
                    db.Dispose();
                    db = null;
                }
            }
        }
    }
    View Code

    BLL 代码

     1 using DAL;
     2 using Model;
     3 using System;
     4 using System.Collections.Generic;
     5 using System.Linq;
     6 using System.Text;
     7 using System.Threading.Tasks;
     8 
     9 namespace BLL
    10 {
    11     public class InfoManage
    12     {
    13         private BaseDal db;
    14         public InfoManage(BaseDal dal)
    15         {
    16             this.db = dal;
    17         }
    18 
    19         public InfoManage()
    20         {
    21             this.db = new BaseDal();
    22         }
    23 
    24 
    25         public bool Add(Info lst)
    26         {
    27             //db.BeginTranscation();
    28             //db.SaveOrUpdate(lst, true);
    29             //return db.Commit() > 0;
    30             return db.SaveOrUpdate(lst, true, true);
    31         }
    32 
    33         public bool Save(Info info)
    34         {
    35             return db.SaveOrUpdate(info, false, true);
    36         }
    37 
    38 
    39         public bool Delete(Info info)
    40         {
    41             return db.DeleteByCondition<Info>(e => e.Name == info.Name, true);
    42         }
    43 
    44         public List<Info> GetList()
    45         {
    46             return db.GetEntity<Info>().ToList();
    47         }
    48     }
    49 }
    View Code


    客户端调用

  • 相关阅读:
    Oracle SQL语句大全—查看表空间
    Class to disable copy and assign constructor
    在moss上自己总结了点小经验。。高手可以飘过 转贴
    在MOSS中直接嵌入ASP.NET Page zt
    Project Web Access 2007自定义FORM验证登录实现 zt
    SharePoint Portal Server 2003 中的单一登录 zt
    vs2008 开发 MOSS 顺序工作流
    VS2008开发MOSS工作流几个需要注意的地方
    向MOSS页面中添加服务器端代码的另外一种方式 zt
    状态机工作流的 SpecialPermissions
  • 原文地址:https://www.cnblogs.com/luoyefeiwu/p/4273292.html
Copyright © 2011-2022 走看看