搭建一個簡單的開發框架 mvc+ef+autofac+sql

先創建一個項目,項目名稱爲MyProject

 選擇mvc模板

 創建一個類庫名稱爲MyProject.Model  

再創建一個MyProject.DAL類庫 

再創建一個MyProject.BLL類庫

然後用Nuget下載類庫:

在BLL層需要EF類庫,DAL層需要EF和Autofac類庫,Model需要EF類庫,Web 層需要EF類庫 

在默認項目 選擇DAL 

寫上Enable-Migrations 會創建 Migrations文件夾 添加數據時 寫入命令Add-Migration all_1(隨意命名不能重複) 更新數據命令Update-Database

然後互相引用 DAL引用Model層,BLL引用DAL類庫,WEB層引用BLL和Model層;

在model類庫添加Entity和Mapping文件夾;

 

 

 在Entity裏面創建一個TUsers類:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyProject.Model
{
    public class TUsers
    {
        public Guid ID { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
    }
}
在Mapping創建一個TUsersMap類:

using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyProject.Model
{
    public class TUsersMap: EntityTypeConfiguration<TUsers>
    {
        public TUsersMap()
        {
            this.HasKey(t => t.ID);
            this.ToTable("TUsers");
            this.Property(t => t.ID).HasColumnName("ID");
            this.Property(t => t.Name).HasColumnName("Name");
            this.Property(t => t.Password).HasColumnName("Password");
        }
    }
}
   

在DAL層

創建UnitOfWork類:

using Autofac;
using Autofac.Core;
using MyProject.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace MyProject.DAL
{
    public class UnitOfWork : DbContext
    {
        public UnitOfWork() : base("name=MyProjectDBContext")//web連接數據庫的配置
        {

        }
        //創建DBContext
        public static DbContext Create()
        {
            DbContext dbContext = CallContext.GetData("DbContext") as DbContext;
            if (dbContext == null)
            {
                dbContext = new UnitOfWork();
                CallContext.SetData("DbContext", dbContext);
            }
            return dbContext;
        }
        #region DbSet
        public virtual DbSet<TUsers> TUsers { get; set; }
        #endregion
        #region Mapping
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
            //Add entity configurations in a structured way using 'TypeConfiguration’ classes
            modelBuilder.Configurations.Add(new TUsersMap());
        }
        #endregion
        #region IOC 容器
        public static IContainer container = null;

        /// <summary>
        /// 獲取 IDal 的實例化對象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T Resolve<T>()
        {
            try
            {
                if (container == null)
                {
                    Initialise();
                }
            }
            catch (System.Exception ex)
            {
                throw new System.Exception("IOC實例化出錯!" + ex.Message);
            }

            return container.Resolve<T>();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public static void Initialise()
        {
            var builder = new ContainerBuilder();
            //格式:builder.RegisterType<xxxx>().As<Ixxxx>().InstancePerLifetimeScope();
            builder.RegisterType<TUsersDAL>().As<ITUsersDAL>().InstancePerLifetimeScope();

            container = builder.Build();
        }
        #endregion
    }
}
添加Repository類:

using MyProject.DAL;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace MyProject.DAL
{
    public class Repository<T> : IRepository<T> where T : class
    {
        private DbContext dbContext = UnitOfWork.Create();
        public void Add(T t)
        {
            dbContext.Set<T>().Add(t);
        }
        public void Delete(T t)
        {
            dbContext.Set<T>().Remove(t);
        }

        public void Update(T t)
        {
            dbContext.Entry(t).State = System.Data.Entity.EntityState.Modified;


        }

        public IQueryable<T> GetList(Expression<Func<T, bool>> whereLambda)
        {
            return dbContext.Set<T>().Where(whereLambda);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="type"></typeparam>
        /// <param name="pageSize">條數</param>
        /// <param name="pageIndex">第幾頁</param>
        /// <param name="isAsc">是否升序</param>
        /// <param name="OrderByLambda">排序字段</param>
        /// <param name="WhereLambda">查詢條件</param>
        /// <returns></returns>
        public IQueryable<T> GetListByPage<type>(int pageSize, int pageIndex, bool isAsc,
            Expression<Func<T, type>> OrderByLambda, Expression<Func<T, bool>> WhereLambda)
        {
            //是否升序
            if (isAsc)
            {
                return dbContext.Set<T>().Where(WhereLambda).OrderBy(OrderByLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            else
            {
                return dbContext.Set<T>().Where(WhereLambda).OrderByDescending(OrderByLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
        }
        /// <summary>
        /// 通過條件獲取一條數據
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public T FirstOrDefault(Expression<Func<T, bool>> whereLambda)
        {
            return dbContext.Set<T>().FirstOrDefault(whereLambda);
        }
        public bool SaveChanges()
        {
            return dbContext.SaveChanges() > 0;
        }
    }
}
添加IRepository類:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace MyProject.DAL
{
    public interface IRepository<T> where T : class
    {
        void Add(T t);
        void Delete(T t);
        void Update(T t);
        IQueryable<T> GetList(Expression<Func<T, bool>> whereLambda);
        IQueryable<T> GetListByPage<type>(int pageSize, int pageIndex, bool isAsc, Expression<Func<T, type>> OrderByLambda, Expression<Func<T, bool>> WhereLambda);
        bool SaveChanges();
        T FirstOrDefault(Expression<Func<T, bool>> whereLambda);
    }
}
創建TUsersDAL和ITUsersDAL類

using MyProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyProject.DAL
{
    public class TUsersDAL : Repository<TUsers>, ITUsersDAL
    {

    }
}

using MyProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyProject.DAL
{
    public interface ITUsersDAL : IRepository<TUsers>
    {
    }
}
 

在BLL層

創建TUserBLL和ITUserBLL類

using MyProject.DAL;
using MyProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyProject.BLL
{
    public class TUserBLL: ITUserBLL
    {
        private ITUsersDAL TUsersDAL = UnitOfWork.Resolve<ITUsersDAL>();
        public List<TUsers> GetList()
        {
            return TUsersDAL.GetList(o => true).ToList();
        }
    }
}
 

using MyProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyProject.BLL
{
    public interface ITUserBLL
    {
        List<TUsers> GetList();
    }
}
 

在Web層

在HomeController控制器中調用ITUserBLL裏面寫的方法

   private ITUserBLL _TUser_BLL = new TUserBLL();
        public ActionResult Index()
        {
            var list = _TUser_BLL.GetList();
            return View(list);
        }

 

發佈了11 篇原創文章 · 獲贊 11 · 訪問量 5442
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章