搭建一个简单的开发框架 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章